C# creating an implicit conversion for generic class?

后端 未结 3 1715
粉色の甜心
粉色の甜心 2020-12-19 01:46

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

相关标签:
3条回答
  • 2020-12-19 02:12

    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.

    0 讨论(0)
  • 2020-12-19 02:17

    This class shows conversion between T and MyClass, both ways.

    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;
      }
    }
    
    0 讨论(0)
  • 2020-12-19 02:17

    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);
    }
    
    0 讨论(0)
提交回复
热议问题