C# 在运行时c确定占位符的类型# public void比较(T someobject) { ..... ..... }
现在我想在运行时确定C# 在运行时c确定占位符的类型# public void比较(T someobject) { ..... ..... },c#,.net,generics,methods,C#,.net,Generics,Methods,现在我想在运行时确定T的类型,并在此基础上执行不同的操作。我尝试过使用typeof,但没有效果。typeof在运行时应该可以正常工作 public void compare<T>(T someobject) { ..... ..... } public void比较(T someobject) { if(typeof(T)=typeof(int)) { //做事 } else if(typeof(T)=typeof(other)) { //做其他事情 } } typeof在
T
的类型,并在此基础上执行不同的操作。我尝试过使用typeof
,但没有效果。typeof在运行时应该可以正常工作
public void compare<T>(T someobject)
{
.....
.....
}
public void比较(T someobject)
{
if(typeof(T)=typeof(int))
{
//做事
}
else if(typeof(T)=typeof(other))
{
//做其他事情
}
}
typeof在运行时应该可以正常工作
public void compare<T>(T someobject)
{
.....
.....
}
public void比较(T someobject)
{
if(typeof(T)=typeof(int))
{
//做事
}
else if(typeof(T)=typeof(other))
{
//做其他事情
}
}
可以试试
public void compare<T>(T someobject)
{
if (typeof(T) == typeof(int))
{
// do stuff
}
else if (typeof(T) == typeof(something else))
{
// do other stuff
}
}
例如:
typeof(T) == typeof(desiredType)
可以试试
public void compare<T>(T someobject)
{
if (typeof(T) == typeof(int))
{
// do stuff
}
else if (typeof(T) == typeof(something else))
{
// do other stuff
}
}
例如:
typeof(T) == typeof(desiredType)
is
可用于检查参数类型
typeof(T) == typeof(int)
或者,或者
if (someobject is SomeType)//...
is
可用于检查参数类型
typeof(T) == typeof(int)
或者,或者
if (someobject is SomeType)//...
typeof(T)
确实应该有效。您使用typeof
究竟尝试了什么?typeof(T)
将提供调用该方法时使用的编译时类型,而不是someObject的实际类型。如果调用compare((object)1)
您想要System.object
还是System.Int32
typeof(T)
将提供前者,而someObject.GetType()
将提供后者。typeof(T)
确实可以。您使用typeof
究竟尝试了什么?typeof(T)
将提供调用该方法时使用的编译时类型,而不是someObject的实际类型。如果调用compare((object)1)
您想要System.object
还是System.Int32
typeof(T)
会给你前者,而someObject.GetType()
会给你后者。当我做typeof(T)==int
时,它说无效表达式项int
请看我的编辑,stackoverflow回答框需要智能感知,Lol当我做typeof(T)==int
时,它说无效表达式项int
请看我的编辑,stackoverflow应答框需要智能感知,LOL是T
无法使用T
因为T
是Typedecriptor
不是Type
哦,我的错,我看到你在检查某个对象不是T
:),is
将在这种情况下工作:)is
不会与T
一起工作,因为T
是typedescriptor
而不是Type
哦,我的错,我看到你检查someobject
而不是T
),is
将在这种情况下工作:)