C#中的通用属性 [英] Generic Property in C#
问题描述
可能存在重复:
制作一个通用属性
我不太确定如何这样做,但我想要做的是创建一个特殊类型的属性,将执行 get
和 set
,并且将在通用类型上定义。
例如,当写这个时:
MyProp< String>名称;
预定义获得
和 set
将在字符串值上执行。
这怎么做?
$
您可以像这样创建一个泛型类:
public class MyProp< T>
{
private T _value;
public T Value
{
get
{
//在此处插入所需的逻辑
return _value;
}
set
{
//在此处插入所需的逻辑
_value = value;
public static implicit operator T(MyProp< T> value)
{
return value.Value;
public static implicit operator MyProp< T>(T value)
{
return new MyProp< T> {Value = value};
$ / code $ / pre
...然后在像这样的类中使用它:
class SomeClass
{
public MyProp< int> SomeProperty {get;组; }
}
隐式运算符意味着您不需要显式设置或获取 Value
属性 MyProp
,但可以编写代码以更自然的方式访问该值:
SomeClass instance = new SomeClass();
instance.SomeProperty = 32;
int someInt = instance.SomeProperty;
Possible Duplicate:
Making a generic property
I'm not quite sure how to do that, but what I would like to do is to create a special type of property that will perform specific tasks at the get
and set
, and will be defined on generic type.
For example, when writing this:
MyProp<String> name;
a pre-defined get
and set
will be performed on the string value.
How can that be done?
Thanks!
解决方案 You can make a generic class like this:
public class MyProp<T>
{
private T _value;
public T Value
{
get
{
// insert desired logic here
return _value;
}
set
{
// insert desired logic here
_value = value;
}
}
public static implicit operator T(MyProp<T> value)
{
return value.Value;
}
public static implicit operator MyProp<T>(T value)
{
return new MyProp<T> { Value = value };
}
}
...then use it in a class like so:
class SomeClass
{
public MyProp<int> SomeProperty { get; set; }
}
The implicit operators means that you do not need to explicitly set or get the Value
property of MyProp
, but can write code to access the value in a more "natural" way:
SomeClass instance = new SomeClass();
instance.SomeProperty = 32;
int someInt = instance.SomeProperty;
这篇关于C#中的通用属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!