开发者

How do i assigned the type of any object to a .NET generic method?

开发者 https://www.devze.com 2022-12-24 21:01 出处:网络
Suppose that I have created a method like this private void Test<t>(t str) { } Now 开发者_开发百科from another method i call it

Suppose that I have created a method like this

private void Test<t>(t str)
{

}

Now 开发者_开发百科from another method i call it

private void BtnClick()
{
    string a = "";


    test<Here I Want To assign The Type what ever the type of 'a' is>();
}

How can I do this ?


Well, if a is a string, you can write:

Test<string>(a);

And if a is an int, you can write:

Test<int>(a);

Pretty obvious. If you don't know the type of a upfront, that means that BtnClick should be generic, the problem would be moved to BtnClick's caller:

private void BtnClick<T>()
{
    T a = ...;


    Test<T>(a);
}

C# 2.0 and later offers type inference, so you wouldn't have to specify the type:

Test(a);


You simply call the function passing a as the parameter. Type inference will determine what T should be for a.

static void Main()
{
    string temp = "blah";
    Test(temp);
    Console.Read();
}

private static void Test<T>(T input)
{
    Console.WriteLine(typeof(T).ToString());
} 

System.String would be printed to the console.

Edit: But, yes, absent type inference, and when you know what your type your variable is, you can always be explicit with the type. Test<string>(temp);


In your example, a is always a string, so you can simply use either Test<string>(a) or Test(a). If, however, you mean that you have a Type instance hanging around somewhere, then you get into the area of reflection. Note that this works, but is slow if used in a tight-loop, so make sure that you understand the performance aspect;

        object arg = ...;
        MethodInfo method = typeof(YourType)
            .GetMethod("Test", BindingFlags.NonPublic | BindingFlags.Instance)
            .MakeGenericMethod(arg.GetType());
        method.Invoke(this, new object[] { arg });
0

精彩评论

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

关注公众号