开发者

Call a method of type parameter

开发者 https://www.devze.com 2023-01-09 21:47 出处:网络
Is there any way to do code such this: class GenericClass<T> { void functionA() { T.A(); } } Or, how to call a function of type pa开发者_开发知识库rameter (type is some my custom class).Re:

Is there any way to do code such this:

class GenericClass<T>
{
    void functionA()
    {
        T.A();
    }
}

Or, how to call a function of type pa开发者_开发知识库rameter (type is some my custom class).


Re:

T.A();

You can't call static methods of the type-parameter, if that is what you mean. You would do better to refactor that as an instance method of T, perhaps with a generic constraint (where T : SomeTypeOrInterface, with SomeTypeOrInterface defining A()). Another alternative is dynamic, which allows duck-typing of instance methods (via signature).

If you mean that the T is only known at runtime (as a Type), then you would need:

typeof(GenericClass<>).MakeGenericType(type).GetMethod(...).Invoke(...);


To call a method of a generic type object you have to instantiate it first.

public static void RunSnippet()
{
    var c = new GenericClass<SomeType>();
}

public class GenericClass<T> where T : SomeType, new()
{
    public GenericClass(){
        (new T()).functionA();
    }   
}

public class SomeType
{
    public void functionA()
    {
        //do something here
        Console.WriteLine("I wrote this");
    }
}


I think you are looking for generic type constraints:

class GenericClass<T> where T : MyBaseClass
{
    void functionA<T>(T something)
    {
        something.A();
    }
}

In terms of the code you posted - in order to call something on T, you will need to pass it as a parameter to functionA. The constraint you use will have to ensure that any T has an A method that can be used.


I understand from your code that you want to call a type parameter static method, and that's just impossible.

See here for more info : Calling a static method on a generic type parameter

0

精彩评论

暂无评论...
验证码 换一张
取 消