Reflection C#-在运行时确定属性是类型还是对象实例?

Reflection C#-在运行时确定属性是类型还是对象实例?,reflection,types,runtime,instance,Reflection,Types,Runtime,Instance,我想确定是否将MyBindingSource.DataSource分配给设计器集Type,或者是否已为其分配了对象实例。这是我目前(相当丑陋)的解决方案: Type sourceT = MyBindingSource.DataSource.GetType(); if( sourceT == null || sourceT.ToString().Equals("System.RuntimeType") ) { return null; } return (ExpectedObjType)

我想确定是否将
MyBindingSource.DataSource
分配给设计器集
Type
,或者是否已为其分配了对象实例。这是我目前(相当丑陋)的解决方案:

Type sourceT = MyBindingSource.DataSource.GetType();
if( sourceT == null || sourceT.ToString().Equals("System.RuntimeType") ) {
     return null;
}
return (ExpectedObjType) result;
System.RuntimeType
是私有的,不可访问,因此我无法执行此操作:

Type sourceT = MyBindingSource.DataSource.GetType();
if ( object.ReferenceEquals(sourceT, typeof(System.RuntimeType)) ) {
     return null;
}
return (ExpectedObjType) result;

我只是想知道是否有更好的解决办法?特别是不依赖
类型
名称的类型。

因为
System.RuntimeType
是从
System.Type
派生而来的。您应该能够执行以下操作:

object result = MyBindingSource.DataSource;
if (typeof(Type).IsAssignableFrom(result.GetType()))
{
    return null;
}
return (ExpectedObjType)result;
或者更简洁地说:

object result = MyBindingSource.DataSource;
if (result is Type)
{
    return null;
}
return (ExpectedObjType)result;
巧合的是,这就是所采用的方法。

你不必去尝试它;您应该能够通过GetType()访问它的名称(这几乎是一样的)。不管怎样,因为它是一个私有类,不能从开发人员代码中访问,所以如果需要验证它是否是一个特定的运行时类型,我认为您必须使用“神奇字符串”。并非所有的“最佳解决方案”都像我们希望的那样优雅

如果您得到的所有类型参数实际上都是RuntimeType对象,那么您可以按照另一个答案中的建议查找基类。然而,如果您可以接收到一个不是RuntimeType的类型,您将得到一些“误报”