Cast object to method generic type

▼魔方 西西 提交于 2021-02-16 13:00:44

问题


This generates an error saying I cannot convert type ClassType to T. Is there any workaround for this?

Is there any way to specify that the type of this can in fact be converted to T?

public void WorkWith<T>(Action<T> method)
{
    method.Invoke((T)this);
}

回答1:


Two possible solutions:

Not type-safe:

public void WorkWith<T>(Action<T> method)
{
    method.Invoke((T)(object)this);
}

This isn't typesafe because you can pass it any method that has a single parameter and no return value, like:

WorkWith((string x) => Console.WriteLine(x));

The typesafe "version" (using generic constraints):

public class MyClass
{
    public void WorkWith<T>(Action<T> method) where T : MyClass
    {
        method.Invoke((T)this);
    }
}

The point here is that to be able to cast this to T, the compiler wants to be sure that this is always castable to T (so the need for the constraint). As shown in the not-type-safe example, the "classical" (unsafe) solution used with generics is passing through a cast to object.




回答2:


public void WorkWith<T>(Action<T> method) where T: ClassType    {
    method.Invoke((T)this);
}


来源:https://stackoverflow.com/questions/35629885/cast-object-to-method-generic-type

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