gpt4 book ai didi

reflection - C# - 在运行时确定属性是 Type 还是 Object 实例?

转载 作者:行者123 更新时间:2023-12-02 02:30:53 25 4
gpt4 key购买 nike

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

Type sourceT = MyBindingSource.DataSource.GetType();
if( sourceT == null || sourceT.ToString().Equals("System.RuntimeType") ) {
return null;
}
return (ExpectedObjType) result;

System.RuntimeType 是私有(private)且不可访问的,所以我不能这样做:

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

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

最佳答案

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

关于reflection - C# - 在运行时确定属性是 Type 还是 Object 实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3841478/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com