백엔드 개발 C#.Net 튜토리얼 C# 기본 지식 정리 기본 지식(17) ILiest 인터페이스 - 제네릭

C# 기본 지식 정리 기본 지식(17) ILiest 인터페이스 - 제네릭

Feb 11, 2017 pm 01:48 PM

ArrayList에 값 유형을 삽입하면 boxing 작업이 트리거되고 값 유형을 검색하려면

1

2

3

4

5

6

7

8

9

ArrayList myArrayList = new ArrayList();

 

myArrayList.Add(40);//装箱

 

myArrayList.Add(80);//装箱

 

Int32 a1 = (Int32)myArrayList[0];//拆箱

 

Int32 a2 = (Int32)myArrayList[1];//拆箱

로그인 후 복사

와 같이 unboxing이 필요하므로 성능 소모가 발생합니다. 포장에 대한 자세한 설명은 다음 글을 참고하세요.
이러한 문제를 해결하기 위해 C#에는 제네릭을 지원하는 IList 인터페이스가 있습니다. 실제로 구조는 IList와 동일하지만 제네릭이 추가되어 있습니다.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

338

339

340

341

342

343

344

345

346

347

348

349

350

351

352

353

354

355

356

357

358

359

360

361

362

363

364

365

366

367

368

369

370

371

372

373

374

375

376

377

378

379

380

381

382

383

384

385

386

387

388

389

390

391

392

393

394

395

396

397

398

399

400

401

402

403

404

405

406

407

408

409

410

411

412

413

414

415

416

417

418

419

420

421

422

423

424

425

426

427

428

429

430

431

432

433

434

435

436

437

438

439

440

441

442

443

444

445

446

447

448

449

450

451

452

453

454

455

456

457

458

459

460

461

462

463

464

465

466

467

468

469

470

471

472

473

474

475

476

477

478

479

480

481

482

483

484

485

486

487

488

489

490

491

492

493

494

495

496

497

498

499

500

501

502

503

504

505

506

507

508

509

510

511

512

513

514

515

516

517

518

519

520

521

522

523

524

525

526

527

528

529

530

531

532

533

534

535

536

537

538

539

540

541

542

543

544

545

546

547

548

549

550

551

552

553

554

/// <summary>

   /// 泛型集合类

   /// </summary>

   /// <typeparam name="T"></typeparam>

   public class List<T> : IList<T>, IList

   {

       /// <summary>

       /// 泛型迭代器

       /// </summary>

       /// <typeparam name="T"></typeparam>

       public struct Enumertor<T> : IEnumerator, IEnumerator<T>

       {

           //迭代索引

           private int index;

 

           //迭代器所属的集合对象引用

           private List<T> list;

 

           public Enumertor(List<T> container)

           {

               this.list = container;

 

               this.index = -1;

           }

 

           public void Dispose()

           {

           }

 

          /// <summary>

          /// 显示实现IEnumerator的Current属性

          /// </summary>

           object IEnumerator.Current

           {

               get

               {

                   return list[index];

               }

           }

 

           /// <summary>

           /// 实现IEnumerator<T>的Current属性

           /// </summary>

           public T Current

           {

               get

               {

                   return list[index];

               }

           }

 

           /// <summary>

           /// 迭代器指示到下一个数据位置

           /// </summary>

           /// <returns></returns>

           public bool MoveNext()

           {

               if (this.index < list.Count)

               {

                   ++this.index;

               }

 

               return this.index < list.Count;

           }

 

           public void Reset()

           {

               this.index = -1;

           }

       }

 

       /// <summary>

       /// 保存数据的数组,T类型则体现了泛型的作用。

       /// </summary>

       private T[] array;

 

       /// <summary>

       /// 当前集合的长度

       /// </summary>

       private int count;

 

       /// <summary>

       /// 默认构造函数

       /// </summary>

       public List()

           : this(1)

       {

 

       }

 

       public List(int capacity)

       {

           if (capacity < 0)

           {

               throw new Exception("集合初始长度不能小于0");

           }

 

           if (capacity == 0)

           {

               capacity = 1;

           }

 

           this.array = new T[capacity];

       }

 

       /// <summary>

       /// 集合长度

       /// </summary>

       public int Count

       {

           get

           {

               return this.count;

           }

       }

 

       /// <summary>

       /// 集合实际长度

       /// </summary>

       public int Capacity

       {

           get

           {

               return this.array.Length;

           }

       }

 

       /// <summary>

       /// 是否固定大小

       /// </summary>

       public bool IsFixedSize

       {

           get

           {

               return false;

           }

       }

 

       /// <summary>

       /// 是否只读

       /// </summary>

       public bool IsReadOnly

       {

           get

           {

               return false;

           }

       }

 

       /// <summary>

       /// 是否可同属性

       /// </summary>

       public bool IsSynchronized

       {

           get

           {

               return false;

           }

       }

 

       /// <summary>

       /// 同步对象

       /// </summary>

       public object SyncRoot

       {

           get

           {

               return null;

           }

       }

 

       /// <summary>

       /// 长度不够时,重新分配长度足够的数组

       /// </summary>

       /// <returns></returns>

       private T[] GetNewArray()

       {

           return new T[(this.array.Length + 1) * 2];

       }

 

       /// <summary>

       /// 实现IList<T>Add方法

       /// </summary>

       /// <param name="value"></param>

       public void Add(T value)

       {

           int newCount = this.count + 1;

 

           if (this.array.Length < newCount)

           {

               T[] newArray = GetNewArray();

 

               Array.Copy(this.array, newArray, this.count);

 

               this.array = newArray;

           }

 

           this.array[this.count] = value;

 

           this.count = newCount;

       }

 

       /// <summary>

       /// 向集合末尾添加对象

       /// </summary>

       /// <param name="value"></param>

       /// <returns></returns>

        int IList.Add(object value)

       {

           ((IList<T>)this).Add((T)value);

 

           return this.count - 1;

       }

 

       /// <summary>

       /// 实现IList<T>索引器

       /// </summary>

       /// <param name="index"></param>

       /// <returns></returns>

       public T this[int index]

       {

           get

           {

               if (index < 0 || index >= this.count)

               {

                   throw new ArgumentOutOfRangeException("index");

               }

 

               return this.array[index];

           }

 

           set

           {

               if (index < 0 || index >= this.count)

               {

                   throw new ArgumentOutOfRangeException("index");

               }

 

               this.array[index] = value;

           }

       }

 

       /// <summary>

       /// 显示实现IList接口的索引器

       /// </summary>

       /// <param name="index"></param>

       /// <returns></returns>

       object IList.this[int index]

       {

           get

           {

               return ((IList<T>)this)[index];

           }

 

           set

           {

               ((IList<T>)this)[index] = (T)value;

           }

       }

 

       /// <summary>

       /// 删除集合中的元素

       /// </summary>

       /// <param name="index"></param>

       /// <param name="count"></param>

       public void RemoveRange(int index, int count)

       {

           if (index < 0)

           {

               throw new ArgumentOutOfRangeException("index");

           }

 

           int removeIndex = index + count;

 

           if (count < 0 || removeIndex > this.count)

           {

               throw new ArgumentOutOfRangeException("index");

           }

 

           Array.Copy(this.array, index + 1, this.array, index + count - 1, this.count - removeIndex);

 

           this.count -= count;

       }

 

       /// <summary>

       /// 实现IList<T>接口的indexOf方法

       /// </summary>

       /// <param name="value"></param>

       /// <returns></returns>

       public int IndexOf(T value)

       {

           int index = 0;

 

           if (value == null)

           {

               while (index < this.count)

               {

                   if (this.array[index] == null)

                   {

                       return index;

                   }

 

                   ++index;

               }

           }

           else

           {

               while (index < this.count)

               {

                   if (value.Equals(this.array[index]))

                   {

                       return index;

                   }

 

                   ++index;

               }

           }

           return -1;

       }

 

       /// <summary>

       /// 显示实现IList接口的IndexOf方法

       /// </summary>

       /// <param name="value"></param>

       /// <returns></returns>

        int IList.IndexOf(object value)

       {

           return ((IList<T>)this).IndexOf((T)value);

       }

 

       /// <summary>

       /// 查找对应数组项

       /// </summary>

       /// <param name="o"></param>

       /// <param name="compar"></param>

       /// <returns></returns>

       public int IndexOf(object o, IComparer compar)

       {

           int index = 0;

 

           while (index < this.count)

           {

               if (compar.Compare(this.array[index], o) == 0)

               {

                   return index;

               }

 

               ++index;

           }

 

           return -1;

       }

 

       /// <summary>

       /// 实现IList<T>接口的Remove方法

       /// </summary>

       /// <param name="value"></param>

       /// <returns></returns>

       public bool Remove(T value)

       {

           int index = this.IndexOf(value);

 

           if (index >= 0)

           {

               this.RemoveRange(index, 1);

 

               return true;

           }

 

           return false;

       }

 

       /// <summary>

       /// 显示实现IList接口的Remove方法,此处显示实现

       /// </summary>

       /// <param name="value"></param>

       void IList.Remove(object value)

       {

           ((IList<T>)this).Remove((T)value);

       }

 

       /// <summary>

       /// 从集合指定位置删除对象的引用

       /// </summary>

       /// <param name="index"></param>

       public void RemoveAt(int index)

       {

           RemoveRange(index, 1);

       }

 

       /// <summary>

       /// 弹出集合的最后一个元素

       /// </summary>

       /// <returns></returns>

       public object PopBack()

       {

           object o = this.array[this.count - 1];

 

           RemoveAt(this.count - 1);

 

           return o;

       }

 

       /// <summary>

       /// 弹出集合第一个对象

       /// </summary>

       /// <returns></returns>

       public object PopFront()

       {

           object o = this.array[0];

 

           RemoveAt(0);

 

           return o;

       }

 

       /// <summary>

       /// 实现IList<T>接口的Insert方法

       /// </summary>

       /// <param name="index"></param>

       /// <param name="value"></param>

       public void Insert(int index, T value)

       {

           if (index >= this.count)

           {

               throw new ArgumentOutOfRangeException("index");

           }

 

           int newCount = this.count + 1;

 

           if (this.array.Length < newCount)

           {

               T[] newArray = GetNewArray();

 

               Array.Copy(this.array, newArray, index);

 

               newArray[index] = value;

 

               Array.Copy(this.array, index, newArray, index + 1, this.count - index);

 

               this.array = newArray;

           }

           else

           {

               Array.Copy(this.array, index, this.array, index + 1, this.count - index);

 

               this.array[index] = value;

           }

 

           this.count = newCount;

       }

 

       /// <summary>

       /// 显示实现IList接口的Insert方法

       /// </summary>

       /// <param name="index"></param>

       /// <param name="value"></param>

       void IList.Insert(int index, object value)

       {

           ((IList<T>)this).Insert(index, (T)value);

       }

 

       /// <summary>

       /// 实现IList<T>接口的Contains方法

       /// </summary>

       /// <param name="value"></param>

       /// <returns></returns>

       public bool Contains(T value)

       {

           return this.IndexOf(value) >= 0;

       }

 

       /// <summary>

       /// 显示实现IList<T>接口的Contains方法

       /// </summary>

       /// <param name="value"></param>

       /// <returns></returns>

       bool IList.Contains(object value)

       {

           return ((IList<T>)this).IndexOf((T)value) >= 0;

       }

 

       /// <summary>

       /// 将集合压缩为实际长度

       /// </summary>

       public void TrimToSize()

       {

           if (this.array.Length > this.count)

           {

               T[] newArray = null;

 

               if (this.count > 0)

               {

                   newArray = new T[this.count];

 

                   Array.Copy(this.array, newArray, this.count);

               }

               else

               {

                   newArray = new T[1];

               }

 

               this.array = newArray;

           }

       }

 

       /// <summary>

       /// 清空集合

       /// </summary>

       public void Clear()

       {

           this.count = 0;

       }

 

       /// <summary>

       /// 实现IEnumerable接口的GetEnumerator方法

       /// </summary>

       /// <returns></returns>

       public IEnumerator<T> GetEnumerator()

       {

           Enumertor<T> ator = new Enumertor<T>(this);

 

           return ator;

       }

 

       /// <summary>

       /// 显示实现IEnumerable接口的GetEnumerator方法

       /// </summary>

       /// <returns></returns>

       IEnumerator IEnumerable.GetEnumerator()

       {

           return ((IEnumerable<T>)this).GetEnumerator();

       }

 

       /// <summary>

       /// 实现ICollection<T>接口的CopyTo方法

       /// </summary>

       /// <param name="array"></param>

       /// <param name="index"></param>

       public void CopyTo(T[] array, int index)

       {

           Array.Copy(this.array, 0, array, index, this.count);

       }

 

       /// <summary>

       /// 显示实现实现ICollection<T>接口的CopyTo方法

       /// </summary>

       /// <param name="array"></param>

       /// <param name="index"></param>

       void ICollection.CopyTo(Array array, int index)

       {

           Array.Copy(this.array, 0, array, index, this.count);

       }

   }

로그인 후 복사

전화:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

static void Main(string[] args)

       {

           //由于已经指定了int,因此加入值类型不会有装箱拆箱操作。

           List<int> tList = new List<int>();

 

           tList.Add(25);

 

           tList.Add(30);

 

           foreach (int n in tList)

           {

               Console.WriteLine(n);

           }

 

           Console.ReadLine();

       }

로그인 후 복사

위는 C#의 기본 지식 내용입니다. (17) ILiest 인터페이스 - Generics에 대한 자세한 내용은 주의하시기 바랍니다. PHP 중국어 넷(www.php.cn)!


본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

<gum> : Bubble Gum Simulator Infinity- 로얄 키를 얻고 사용하는 방법
4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
Nordhold : Fusion System, 설명
4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
Mandragora : 마녀 트리의 속삭임 - Grappling Hook 잠금 해제 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

일반 함수가 Golang의 가변 매개변수 유형 문제를 해결합니까? 일반 함수가 Golang의 가변 매개변수 유형 문제를 해결합니까? Apr 16, 2024 pm 06:12 PM

Go의 일반 함수는 가변 유형의 문제를 해결합니다. 일반 함수를 사용하면 런타임에 유형 매개변수를 지정할 수 있습니다. 이를 통해 다양한 유형의 인수를 처리할 수 있는 함수를 작성할 수 있습니다. 예를 들어 Max 함수는 두 개의 비교 가능한 매개변수를 허용하고 더 큰 값을 반환하는 일반 함수입니다. 일반 함수를 사용하면 다양한 유형의 매개변수를 처리할 수 있는 보다 유연하고 일반적인 코드를 작성할 수 있습니다.

golang의 제네릭의 특정 애플리케이션 시나리오 golang의 제네릭의 특정 애플리케이션 시나리오 May 04, 2024 am 11:45 AM

Go의 제네릭 적용 시나리오: 컬렉션 작업: 필터링과 같은 모든 유형에 적합한 컬렉션 작업을 만듭니다. 데이터 구조: 큐, 스택, 맵과 같은 범용 데이터 구조를 작성하여 다양한 유형의 데이터를 저장하고 조작합니다. 알고리즘: 다양한 유형의 데이터를 처리할 수 있는 정렬, 검색, 축소 등의 범용 알고리즘을 작성합니다.

Java 함수 제네릭의 상한과 하한은 무엇입니까? 사용하는 방법? Java 함수 제네릭의 상한과 하한은 무엇입니까? 사용하는 방법? Apr 26, 2024 am 11:45 AM

Java 함수 제네릭을 사용하면 상한 및 하한을 설정할 수 있습니다. 확장은 함수에서 허용하거나 반환하는 데이터 유형이 지정된 유형의 하위 유형이어야 함을 지정합니다. 하한(슈퍼)은 함수에서 허용하거나 반환하는 데이터 유형이 지정된 유형의 슈퍼 유형이어야 함을 지정합니다. 제네릭을 사용하면 코드 재사용성과 보안이 향상됩니다.

Golang 제네릭이 함수 서명 및 매개변수에 미치는 영향은 무엇입니까? Golang 제네릭이 함수 서명 및 매개변수에 미치는 영향은 무엇입니까? Apr 17, 2024 am 08:39 AM

Go 함수 서명 및 매개변수에 대한 제네릭의 영향은 다음과 같습니다. 유형 매개변수: 함수 서명에는 함수가 사용할 수 있는 유형을 지정하는 유형 매개변수가 포함될 수 있습니다. 유형 제약 조건: 유형 매개 변수에는 충족해야 하는 조건을 지정하는 제약 조건이 있을 수 있습니다. 매개변수 유형 유추: 컴파일러는 지정되지 않은 유형 매개변수의 유형을 유추할 수 있습니다. 유형 지정: 일반 함수를 호출하기 위해 매개변수 유형을 명시적으로 지정할 수 있습니다. 이를 통해 코드 재사용성과 유연성이 향상되어 여러 유형과 함께 사용할 수 있는 함수 및 유형을 작성할 수 있습니다.

Android 개발에 Java 제네릭 적용 Android 개발에 Java 제네릭 적용 Apr 12, 2024 pm 01:54 PM

Android 개발에 제네릭을 적용하면 코드 재사용성, 보안 및 유연성이 향상됩니다. 구문은 유형 매개변수화된 데이터를 조작하는 데 사용할 수 있는 유형 변수 T를 선언하는 것으로 구성됩니다. 작동 중인 일반 항목에는 사용자 정의 데이터 어댑터가 포함되어 있어 어댑터가 모든 유형의 사용자 정의 데이터 개체에 적응할 수 있습니다. Android는 또한 다양한 유형의 매개변수를 조작할 수 있는 일반 목록 클래스(예: ArrayList)와 일반 메서드를 제공합니다. 제네릭 사용의 이점에는 코드 재사용성, 보안 및 유연성이 포함되지만, 코드 가독성을 보장하기 위해 올바른 경계를 지정하고 이를 적당히 사용하도록 주의를 기울여야 합니다.

Golang에서 제네릭의 장점과 용도를 살펴보세요. Golang에서 제네릭의 장점과 용도를 살펴보세요. Apr 03, 2024 pm 02:03 PM

답변: Golang 제네릭은 코드 재사용성, 유연성, 유형 안전성 및 확장성을 개선하기 위한 강력한 도구입니다. 자세한 설명: 장점: 코드 재사용성: 공통 알고리즘 및 데이터 구조 유연성: 특정 유형의 인스턴스의 런타임 생성 유형 안전성: 컴파일 시간 유형 확인 확장성: 손쉬운 확장 및 사용자 정의 목적: 공통 기능: 정렬, 비교 목록과 같은 공통 데이터 구조 , 맵, 스택 등 유형 별칭: 유형 선언 단순화 제한된 제네릭: 유형 안전성 보장

Java 열거형 유형은 제네릭과 어떻게 작동합니까? Java 열거형 유형은 제네릭과 어떻게 작동합니까? May 04, 2024 am 08:36 AM

Java에서 열거형 유형과 제네릭의 조합: 제네릭으로 열거형을 선언할 때 꺾쇠 괄호를 추가해야 하며 T는 유형 매개변수입니다. 일반 클래스를 생성할 때 꺾쇠 괄호도 추가해야 합니다. T는 모든 유형을 저장할 수 있는 유형 매개변수입니다. 이 조합은 코드 유연성, 유형 안전성을 향상하고 코드를 단순화합니다.

Java Generics의 장점과 단점 Java Generics의 장점과 단점 Apr 12, 2024 am 11:27 AM

Java Generics의 장점과 단점 Java Generics란 무엇입니까? Java 제네릭을 사용하면 특정 유형뿐만 아니라 모든 유형의 객체를 저장할 수 있는 유형이 지정된 컬렉션과 클래스를 만들 수 있습니다. 이는 코드 유연성과 재사용성을 높이고 오류를 줄입니다. 장점 유형 안전성: 제네릭은 컴파일 타임에 유형 안전성을 강화하여 컬렉션에 호환 가능한 유형의 데이터만 있도록 보장함으로써 런타임 오류를 줄입니다. 재사용성: 코드를 다시 작성할 필요 없이 일반 클래스 및 컬렉션을 다양한 데이터 유형과 함께 사용할 수 있습니다. 유연성: 제네릭을 사용하면 다양한 유형의 데이터를 유연하게 처리할 수 있는 코드를 생성할 수 있어 확장성과 유지 관리성이 향상됩니다. 간결한 코드: 제네릭을 사용하면 코드를 더욱 간결하고 읽기 쉽게 만들 수 있습니다. API 일관성: JavaCollection

See all articles