问题描述
我说的不是一般的类声明的属性或字段与泛型参数的类型。我说的是它可以同时适用于通用和非通用类的一般属性。
I'm not talking about generic classes that declare properties or fields with the type of a generic parameter. I'm talking about generic properties which could be applied to both generic and non-generic classes.
我说的不是这样的:
public class Base<T>
{
public T BaseProperty { get; set; }
}
我说的是这样的:
I'm talking about this:
public class Base
{
public T BaseProperty<T>
{
get
{
// Insert magic
}
set
{
// Insert magic
}
}
}
或者这样:
public class Base<U>
{
public T BaseProperty<T>
{
get
{
// Insert magic
}
set
{
// Insert magic
}
}
public U OtherBaseProperty { get; set; }
}
用法会去是这样的:
The usage would go something like this:
var b = new Base();
b.BaseProperty<int> = 42;
int i = b.BaseProperty<int>;
b.BaseProperty<string> = "Hi";
string s = b.BaseProperty<string>;
或为第二个例子:
Or for the second example:
var b = new Base<string>();
b.BaseProperty<int> = 42;
int i = b.BaseProperty<int>;
b.OtherBaseProperty = "Hi";
string s = b.OtherBaseProperty;
该//插入魔术指处理每次调用通用属性getter或setter具有不同类型的类型参数。
The // Insert Magic refers to handling each call to the generic property getter or setter that has a different type for the type parameter.
例如对于这样的:
b.BaseProperty<int> = 42;
需要不同的处理为:
Needs to be handled differently to:
b.BaseProperty<string> = "Hi";
我会设想,对于每个类型T,如果吸气剂被称为设定器被调用之前则默认(T),则返回。当设置器叫做值存储每类型T,使得当吸气剂随后称为被该类型返回设置previous值
I would envisage that for each type T if the getter is called before the setter is called then default(T) is returned.When the setter is called the value is stored per type T so that when the getter is subsequently called the previous value that was set for that type is returned.
需要注意的是在幕后的属性只是方法。
Note that under the covers properties are just methods.
你认为这将是有益的?
推荐答案
我有好几次,我也喜欢这样做的能力,是的。
I've had a couple of times where I would have liked the ability to do this, yes.
但是,所涉及的语法为pretty的丑陋,这是充分很少有用,我想我preFER只是吮吸它,去用通用的方法。
However, the syntax involved would be pretty ugly, and it's sufficiently rarely useful that I think I prefer to just suck it up and go with generic methods.
这篇关于你认为通用性将是.NET有用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!