C#为generics类创建隐式转换?
我有一个generics类,我曾经把数据写入IsolatedStorage。
我可以使用static implicit operator T()
从我的Generic类转换为Generic Parameter T
例如
MyClass foo = new MyClass(187.0); double t = foo;
我的问题是,我该怎么做呢?
MyClass foo = new MyClass(187.0); double t = 0.2d; foo = t;
隐式运算符必须是静态的,所以我不确定如何传递我的类的实例?
编辑:
如果您希望能够在类中更改T
的值,我建议将其作为属性公开,如:
T Value { get; set; }
这将允许您更改值,而不是隐式运算符返回该类的全新实例的行为。
您可以也可以不使用隐式运算符。 做点什么
public static implicit operator int(MyType m) public static implicit operator MyType(int m)
将隐式地将MyType
转换为int
并将int
转换为MyType
。 但是,你是对的,因为它们是静态的, MyType
的int
必须创建一个新的MyType
实例并返回它。
所以这段代码:
MyClass foo = new MyClass(187.0); double t = 0.2d; foo = t;
不会用t
替换foo
的值,隐式运算符会从t
返回一个全新的 MyClass
并将其赋值给Foo
。
这个类显示了T和MyClass之间的转换。
class MyClass { public MyClass(T val) { Value = val; } public T Value { get; set; } public static implicit operator MyClass (T someValue) { return new MyClass (someValue); } public static implicit operator T(MyClass myClassInstance) { return myClassInstance.Value; } }
您应该能够通过简单地指定另一个隐式运算符来转换另一种方式:
public static implicit operator MyClass(T input) { return new MyClass (input); }