使用字符串或其他格式比较数据类型
本文关键字:格式 比较 数据类型 其他 字符串 | 更新日期: 2023-09-27 18:02:33
我想设置一个数据类型而不必在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)
,但它似乎没有那样工作。或者我没做对
如果你事先(在编译时)知道类型,你应该使用typeof
,只有当你不知道并且在运行时它会改变时才使用GetType
。
另一件事,如果你只需要比较,你可以使用is
关键字,ref:关键字
所以这些都可以:
if(RealFooBar is string)
if(RealFooBar.GetType() == typeof(string))
编辑:添加澄清溶液。尽管第二个例子适用于这个特殊情况,但建议在几乎所有情况下使用is
。原因是第二个例子是"精确类型比较"。并且会使使用继承变得更加困难。给出下面的例子,你可以看到它在类中使用时的行为。
class Foo {}
class Bar : Foo {}
var instanceOfBar = new Bar();
var instanceOfFoo = new Foo();
//works for base class as expected
if(instanceOfFoo is Foo) //true
if(instanceOfFoo is Bar) //false
if(instanceOfFoo.GetType() == typeof(Foo)) //true
if(instanceOfFoo.GetType() == typeof(Bar)) //false
//exact type checks could behave "unexpectedly" for classes that inherit
if(instanceOfBar is Foo) //true
if(instanceOfBar is Bar) //true
if(instanceOfBar.GetType() == typeof(Foo)) //false ???
if(instanceOfBar.GetType() == typeof(Bar)) //true
我在某种意义上使用"意外"这个词,我们无法知道将来何时会有从Foo
继承的新类,并且已经编写的代码可能会停止工作或异常行为