如何在c#中检查变量是否包含Instance或Type

本文关键字:包含 是否 Instance Type 变量 检查 | 更新日期: 2023-09-27 18:22:12

我有一个类Test

public class Test { }

现在我有一个变量object1,它包含Test的一个实例。

object object2 = new Test();
// some code
object2 = typeof(Test);

object2将在不同的场景中接受Test类的类型和实例。我如何检查它的值。即Test的实例或Test 的类型

如何在c#中检查变量是否包含Instance或Type

if (object2 is Test) { ... }
if (object2 is Type) { ... }

但不要那样做。

if (object2 is Type) {...}//当对象2的类型为Type

if (object2 is Test) {...}//当对象2的类型为Test。。因此拥有一个实例

var object2Type = object2 as Type;
if (object2Type != null)
{
    // Do something
}
else
{
    var object2Test = (Test)object2;
    // Do something else
}

您也可以使用我的库(链接):

object2.DetermineType()
       .When((Test target) => { /* action to do */ })
       .When((Type target) => { /* action to do */ })
       .Resolve();

object2.DetermineType()
       .When<Test>(target => { /* action to do */ })
       .When<Type>(target => { /* action to do */ })
       .Resolve();

但如果你必须以这种方式确定类型,那么你的设计可能并不好。

在没有测试的情况下,您可以检查

if (object2 is Test) // .. we have an instance of Test
else if (object2 == typeof(Test)) // we have the second case

Btw我认为这是一个糟糕的设计,因为引入变量的目的只有一个。