简体   繁体   English

在运行时确定占位符的类型c#

[英]determining the type of placeholder at runtime c#

public void compare<T>(T someobject)
{
  .....
  .....
}

Now i want to determine the type of T at runtime and do different operation based upon that. 现在,我想在运行时确定T的类型,并在此基础上执行不同的操作。 I have tried using the typeof but to no avail. 我曾尝试使用typeof但无济于事。

typeof should work fine in runtime. typeof在运行时应该可以正常工作。

    public void compare<T>(T someobject)
    {
        if (typeof(T) == typeof(int))
        {
            // do stuff
        }
        else if (typeof(T) == typeof(something else))
        {
            // do other stuff
        }
    }

is can be used to check the parameter type is可以用来检查参数类型

if (someobject is SomeType)//...

Or, alternatively... 或者,或者...

        Type constructedType = typeof(T);
        if (constructedType == typeof(SomeType))//... 

Can try 可以尝试

typeof(T) == typeof(desiredType)

For example: 例如:

typeof(T) == typeof(int)
    if (someobj.GetType() == typeof(ClassA)) { /* do opertion */},

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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