C#为泛型类创建隐式转换? [英] C# creating an implicit conversion for generic class?
问题描述
我可以使用一个静态隐式运算符T() code>从我的Generic类转换为通用参数
T
eg
MyClass< double> foo = new MyClass(187.0);
double t = foo;
我的问题是,我怎么能做到相反?
MyClass< double> foo = new MyClass(187.0);
double t = 0.2d;
foo = t;
隐式运算符必须是静态的,所以我不确定如何在实例中传递
如果你想要能够更改类中的 T
的值,我建议将它暴露为如下属性:
T Value {get;组; }
这将允许您更改该值,而不是隐式运算符的行为完全返回新类的实例。
你可以也可以不使用隐式运算符。做类似于
public static implicit operator int(MyType m)
public static implicit operator MyType(int m)
会隐式地从 MyType
转换为 int
以及从 int
到 MyType
。然而,你是对的,因为它们是静态的,所以 int
到 MyType
需要创建一个新的实例 MyType
并返回。
所以这段代码:
MyClass的<双> foo = new MyClass(187.0);
double t = 0.2d;
foo = t;
不会取代 foo
在 t
中,隐式运算符会从<$ c $返回全新的 emclass c> t 并将其分配给 Foo
。
I have a generics class that I used to write data to IsolatedStorage.
I can use an static implicit operator T()
to convert from my Generic class to the Generic Parameter T
e.g.
MyClass<double> foo = new MyClass(187.0);
double t = foo;
My question is, how can I do the reverse?
MyClass<double> foo = new MyClass(187.0);
double t = 0.2d;
foo = t;
The implicit operator has to be static, so I'm not sure how I can pass in the instance of my class?
EDIT:
If you want to be able to change the value of T
in your class, I would recommend exposing it as a property like:
T Value { get; set; }
That will allow you to change the value, instead of the behavior of the implicit operator returning an entirely new instance of the class.
You can and can't using implicit operators. Doing something like
public static implicit operator int(MyType m)
public static implicit operator MyType(int m)
will implicitly convert from MyType
to int
and from int
to MyType
respectively. However, you're right, since they are static, the int
to MyType
specifically will have to create a new instance of MyType
and return that.
So this code:
MyClass<double> foo = new MyClass(187.0);
double t = 0.2d;
foo = t;
wouldn't replace the value in foo
with t
, the implicit operator would return an entirely new MyClass
from t
and assign that to Foo
.
这篇关于C#为泛型类创建隐式转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!