Jon*_*ker 7 .net c# generics properties c#-3.0
我不是在讨论声明具有泛型参数类型的属性或字段的泛型类.我在谈论可以应用于泛型和非泛型类的泛型属性.
我不是在说这个:
public class Base<T>
{
public T BaseProperty { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我在说这个:
public class Base
{
public T BaseProperty<T>
{
get
{
// Insert magic
}
set
{
// Insert magic
}
}
}
Run Code Online (Sandbox Code Playgroud)
或这个:
public class Base<U>
{
public T BaseProperty<T>
{
get
{
// Insert magic
}
set
{
// Insert magic
}
}
public U OtherBaseProperty { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
用法将是这样的:
var b = new Base();
b.BaseProperty<int> = 42;
int i = b.BaseProperty<int>;
b.BaseProperty<string> = "Hi";
string s = b.BaseProperty<string>;
Run Code Online (Sandbox Code Playgroud)
或者对于第二个例子:
var b = new Base<string>();
b.BaseProperty<int> = 42;
int i = b.BaseProperty<int>;
b.OtherBaseProperty = "Hi";
string s = b.OtherBaseProperty;
Run Code Online (Sandbox Code Playgroud)
// Insert Magic指的是处理对类型参数具有不同类型的泛型属性getter或setter的每次调用.
例如:
b.BaseProperty<int> = 42;
Run Code Online (Sandbox Code Playgroud)
需要以不同的方式处理:
b.BaseProperty<string> = "Hi";
Run Code Online (Sandbox Code Playgroud)
我会设想对于每个类型T,如果在调用setter之前调用getter,则返回default(T).当调用setter时,每个类型T都存储一个值,这样当随后调用getter时,将返回为该类型设置的先前值.
请注意,封面下的属性只是方法.
你认为这会有用吗?
| 归档时间: |
|
| 查看次数: |
2116 次 |
| 最近记录: |