【问题标题】:C# - Determine at runtime if property is a Type or an Object instance?C# - 在运行时确定属性是类型还是对象实例?
【发布时间】:2011-04-19 23:32:26
【问题描述】:

我想确定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 名称的。

【问题讨论】:

    标签: reflection types runtime instance


    【解决方案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;
    

    巧合的是here采用的方法。

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 2012-08-27
        • 1970-01-01
        • 1970-01-01
        • 2010-11-02
        • 1970-01-01
        • 2013-03-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多