implicitly casting a generic<T> back to T

六月ゝ 毕业季﹏ 提交于 2020-01-01 09:11:46

问题


If I write a generic class like class MyGeneric<T> is it possible to write an implicit cast to type T, so I can do stuff like:

public class MyGeneric<T>
{
...
}

public class GenericProperties
{
   public MyGeneric<string> MyGenericString {get;set;}

   public void UseMyGeneric()
   {
       string sTest = MyGenericString;
       MyGenericString = "this is a test";
   }
}

Is it possible to do that by overloading operators? I know it could be done if my class wasn't a generic...


回答1:


Well, yes, but for the love of zombie jesus do NOT do that. It's really confusing. You're slightly misunderstanding the purpose of generics, I think. It's not used to "turn" a class into that type, it's used to have that type (MyGenericString) be 'aware' of the type you want, for various purposes (typically those are collection-based purposes).




回答2:


yep..but don't over-do it, this tends to confuse people. i would only use it for wrapper types.

class Wrapper<T>
{
    public T Value {get; private set;}
    public Wrapper(T val) {Value = val;}

    public static implicit operator T(Wrapper<T> wrapper) {return wrapper.Value;}
    public static implicit operator Wrapper<T>(T val) {return new Wrapper<T>(val);}
}



var intWrapper = new Wrapper<int>(7);
var usingIt = 7 * intWrapper; //49

Wrapper<int> someWrapper = 9; //woohoo



回答3:


As others have said, that is legal but dangerous. There are many pitfalls you can fall into. For example, suppose you defined a user-defined conversion operator between C<T> and T. Then you say

C<object> c = new C<object>("hello");
object o = (object) c;

What happens? does your user-defined conversion run or not? No, because c is already an object.

Like I said, there are crazy situations you can get into when you try to define generic conversion operators; do not do it unless you have a deep and detailed understanding of section 10.10.3 of the specification.




回答4:


Yes it's possible using implicit Conversion Operator Overloading

class Program
{
    static void Main(string[] args)
    {
        myclass<string> a = new myclass<string>();
        a.inner = "Hello";
        string b = a;
        Console.WriteLine(b);
    }
}

class myclass<T>
{
    public T inner;
    public myclass()
    {

    }
    public static implicit operator T(myclass<T> arg1)
    {
        return arg1.inner;
    }
}


来源:https://stackoverflow.com/questions/2010066/implicitly-casting-a-generict-back-to-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!