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

3

我希望确定 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;

我在想是否存在更好的解决方案?特别是不依赖于Type名称的解决方案。

2个回答

1

由于 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;

巧合的是,这正是这里采用的方法。


1

你不需要使用ToString()方法,你可以通过GetType()方法访问它的名称(这几乎是一样的)。无论哪种方式,因为它是一个私有类,无法从开发人员代码中访问,如果您需要验证它是否特定为RuntimeType,则可能会遇到“魔术字符串”。并非所有“最佳解决方案”都像我们希望的那样优雅。

如果您获得的所有类型参数实际上都是RuntimeType对象,则可以按照另一个答案建议的方式查找基类。但是,如果您收到的类型不是RuntimeType,则会出现一些“误报”。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接