简体   繁体   English

C#为泛型类创建隐式转换?

[英]C# creating an implicit conversion for generic class?

I have a generics class that I used to write data to IsolatedStorage. 我有一个泛型类,我曾经用于将数据写入IsolatedStorage。

I can use an static implicit operator T() to convert from my Generic class to the Generic Parameter T 我可以使用static implicit operator T()从我的Generic类转换为Generic Parameter T

eg 例如

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? 隐式运算符必须是静态的,所以我不确定如何传递我的类的实例?

This class shows conversion between T and MyClass, both ways. 这个类显示了T和MyClass之间的转换。

class MyClass<T>
{
  public MyClass(T val)
  {
     Value = val;
  }

  public T Value { get; set; }

  public static implicit operator MyClass<T>(T someValue)
  {
     return new MyClass<T>(someValue);
  }

  public static implicit operator T(MyClass<T> myClassInstance)
  {
     return myClassInstance.Value;
  }
}

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的值,我建议将其作为属性公开,如:

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. 将隐式地从MyType转换为int并从int转换为MyType 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. 但是,你是对的,因为它们是静态的, MyTypeint特别需要创建一个新的MyType实例并返回它。

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 . 不会用t替换foo的值,隐式运算符会从t返回一个全新的 MyClass并将其赋值给Foo

You should be able to convert the other way by simply specifying another implicit operator: 您应该能够通过简单地指定另一个隐式运算符来转换另一种方式:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM