Mar*_*ell 61
简单地说,您声明一个带有额外标签的类型或方法来指示通用位:
class Foo<T> {
public Foo(T value) {
Value = value;
}
public T Value {get;private set;}
}
Run Code Online (Sandbox Code Playgroud)
以上定义了泛型Foo"of T",其中T由调用者提供.按照惯例,一般类型参数启动与T.如果只有一个,T是好的-否则他们的名字都有效:TSource,TValue,TListType等
与C++模板不同,.NET泛型由运行时提供(不是编译器技巧).例如:
Foo<int> foo = new Foo<int>(27);
Run Code Online (Sandbox Code Playgroud)
所有Ts都已被int上面的替换.如有必要,可以使用约束限制泛型参数:
class Foo<T> where T : struct {}
Run Code Online (Sandbox Code Playgroud)
现在Foo<string>将拒绝编译 - 因为string它不是结构(值类型).有效约束是:
T : class // reference-type (class/interface/delegate)
T : struct // value-type except Nullable<T>
T : new() // has a public parameterless constructor
T : SomeClass // is SomeClass or inherited from SomeClass
T : ISomeInterface // implements ISomeInterface
Run Code Online (Sandbox Code Playgroud)
约束也可以涉及其他泛型类型参数,例如:
T : IComparable<T> // or another type argument
Run Code Online (Sandbox Code Playgroud)
您可以根据需要使用尽可能多的通用参数:
public struct KeyValuePair<TKey,TValue> {...}
Run Code Online (Sandbox Code Playgroud)
其他注意事项:
Foo<int>与其相对Foo<float>.例如:
class Foo<T> {
class Bar<TInner> {} // is effectively Bar<T,TInner>, for the outer T
}
Run Code Online (Sandbox Code Playgroud)
示例1:您想要创建三级类
Class Triple<T1, T2, T3>
{
T1 _first;
T2 _second;
T3 _Third;
}
Run Code Online (Sandbox Code Playgroud)
示例2:将解析给定数据类型的任何枚举值的辅助类
static public class EnumHelper<T>
{
static public T Parse(string value)
{
return (T)Enum.Parse(typeof(T), value);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
62310 次 |
| 最近记录: |