Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#,.net,通用编程体系结构。GetType或Enum:哪个更好?_C#_.net_Types_Enums - Fatal编程技术网

C#,.net,通用编程体系结构。GetType或Enum:哪个更好?

C#,.net,通用编程体系结构。GetType或Enum:哪个更好?,c#,.net,types,enums,C#,.net,Types,Enums,你认为哪一个更好 if (thing.GetType() == typeof(thisthing)) { //do stuff for this type of thing. } 或者为对象指定枚举属性 if (thing.TypeName == NamesEnum.thisthing) { //do stuff for this type of thing.

你认为哪一个更好

        if (thing.GetType() == typeof(thisthing))
        {
           //do stuff for this type of thing.
        }
或者为对象指定枚举属性

        if (thing.TypeName == NamesEnum.thisthing)
        {
           //do stuff for this type of thing.
        }

这两种方法都不是特别可扩展或可维护的方法

通常,最好将其直接设计到类型层次结构中的虚拟方法中,然后只调用该方法。这允许其他类根据需要重写并提供自定义功能


在您的例子中,
thisthing
类型(如果您想遵循.NET命名约定,应该将其命名为
thisthing
)将有一个
DoStuff
方法,如果需要,该方法可以是虚拟的,并调用它。

如果您使用的是没有子类型的基本类型。。。 您的第一个示例可以很好地缩短为

if (thing is typeof(thisthing))
真的要视情况而定。如果你有很多不同的类型,你会在某个时候需要一个switch语句,所以如果有很多类型,我会说选项2。

这取决于:

if (thing.TypeName == NamesEnum.thisthing)
将运行比
GetType()
更高的性能,这是两个数值的简单比较

但是:

更“灵活”:当您进行重构、更改类型名或其他操作时,此条件仍然有效

但如果两个类型属于两个不同的程序集,则在条件下将失败,而在第一种情况下,这仍然将作为相等匹配,因为您不是
类型
,而只是枚举值


简而言之,没有最好的方法,只是最适合您的需要。

请注意,这实际上与OP的检查不同(尽管这更可能是更好的选择)。对于子类和实际类,
is
关键字将返回true,OP的版本要求类型精确匹配。
is
也将匹配子类型,而不仅仅是精确的类型匹配。很好,我假设类型没有子类,你的意思是
东西就是这个东西
?这不是OP问题的答案,当虚拟方法不适用时,有很多有效的情况。
if (thing.GetType() == typeof(thisthing))