Csharp/C#教程:C#为generics类创建隐式转换?分享


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 。 但是,你是对的,因为它们是静态的, MyTypeint必须创建一个新的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; } } 

您应该能够通过简单地指定另一个隐式运算符来转换另一种方式:

上述就是C#学习教程:C#为generics类创建隐式转换?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

 public static implicit operator MyClass(T input) { return new MyClass(input); } 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1006439.html

(0)
上一篇 2021年12月29日
下一篇 2021年12月29日

精彩推荐