2016-08-14 76 views
1

我想设置一个数据类型,而不必在C#中创建额外的变量。而不是创建一个空变量,然后比较一个类型。使用字符串或其他格式比较数据类型

CustomType empty; //empty variable 
CustomType RealFooBar = new CustomType("extremeFoobar", false) //custom datatype with data in it 

if(RealFooBar.GetType() == empty.GetType()) 
    //operation 

我宁愿做这样的:

CustomType RealFooBar // already has data 

if(RealFooBar.GetType() == {CustomType}) 
    //operation 

有没有办法做到这一点?我试过typeof(CustomType)一次,但它似乎没有这样工作。或者我没有做对。

+0

你的“意思似乎没有工作“?假设你的代码没有错误,像'o.GetType()== typeof(Foo)'这样的东西应该给你正确的结果。 –

+0

现在我感到很蠢。无论出于何种原因,它都有效... – Robokitty

回答

2

如果您事先知道类型,并且仅在您不知道的情况下使用GetType,则应该使用typeof,并且在运行时它会改变。

另一件事,如果你只需要你比较能is关键词,参考文献: IS keyword

任何这些应该工作:

if(RealFooBar is string) 
if(RealFooBar.GetType() == typeof(string))