home screen

Search



Number Of Result : 0

Result :


Tuesday, December 2, 2008

Generic Methods

- Purpose :
Thực hiện chức năng với lớp kiểu T ( lớp chưa xác định trước, chị xác định tại thời điểm run-time )
- Systax :

modifier return-type nameOfMethod<TEntity> ( parameters with TEntity type ) where TEntity : ...

- Với cú pháp Where ta có cac ràng buộc bên dưới như sau:



Constraint


Description


where T: struct


The type argument must be a value type. Any value type except Nullable can be specified. See Using Nullable Types (C# Programming Guide) for more information.


where T : class


The type argument must be a reference type; this applies also to any class, interface, delegate, or array type.


where T : new()


The type argument must have a public parameterless constructor. When used together with other constraints, the new() constraint must be specified last.


where T : <base class name>


The type argument must be or derive from the specified base class.


where T : <interface name>


The type argument must be or implement the specified interface. Multiple interface constraints can be specified. The constraining interface can also be generic.


where T : U


The type argument supplied for T must be or derive from the argument supplied for U. This is called a naked type constraint.




- Nếu chúng ta ko sử dụng where để ràng buộc điều kiện cho kiểu T thì sẽ báo lỗi "Compile Error"

public IShape GetRectangle<TEntity>()
{
//báo lỗi tại đây vì chưa chác TEntity chúng ta đưa vào là kiểu được Implement ( hay Inheritance ) từ IShape
return new TEntity()
}


- Ví dụ : trong Method chúng ta muốn NEW 1 Class thuộc lớp Interface IShape

//với where TEntity : IShape , new() cho biết lớp TEntity đưa vào phải được Implement ( hay Inheritance ) từ IShape và có thể được NEW 1 đối tượng
public IShape GetRectangle<TEntity>() where TEntity : IShape , new()
{
return new TEntity()
}


- Usage


//lop RectangleExtra
class RectangleExtra : IShape{...}

interface IShape{...}

public void Method()
{

//khi do shape sẽ là kiểu RectangleExtra
IShape shape = GetRectangle<RectangleExtra>() ;
}

No comments: