简体   繁体   中英

Cast object to method generic type

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);
}
public void WorkWith<T>(Action<T> method) where T: ClassType    {
    method.Invoke((T)this);
}

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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