C# - 在运行时确定属性是类型还是对象实例?
我想确定 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
名称的类型。
I want to determine whether MyBindingSource.DataSource
is assigned to the designer set Type
, or if it has been assigned an object instance. This is my current (rather ugly) solution:
Type sourceT = MyBindingSource.DataSource.GetType();
if( sourceT == null || sourceT.ToString().Equals("System.RuntimeType") ) {
return null;
}
return (ExpectedObjType) result;
The System.RuntimeType
is private and non-accessible, so I can't do this:
Type sourceT = MyBindingSource.DataSource.GetType();
if ( object.ReferenceEquals(sourceT, typeof(System.RuntimeType)) ) {
return null;
}
return (ExpectedObjType) result;
I was just wondering if a better solution exists? Particularly one that doesn't rely on the Type
name.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于
System.RuntimeType
是从System.Type
派生的,您应该能够执行以下操作:或更简洁:
巧合的是,这就是采用的方法 此处。
Since
System.RuntimeType
is derived fromSystem.Type
you should be able to do the following:or even more concisely:
Coincidentally this is the approach adopted here.
你不必 ToString() 它;您应该能够通过 GetType() 访问其名称(这几乎是同一件事)。无论哪种方式,因为它是一个私有类并且无法从开发人员代码访问,所以我认为如果您需要验证它是否是一个特定的 RuntimeType,您就会陷入“魔术字符串”的困境。并非所有“最佳解决方案”都像我们希望的那样优雅。
如果您获得的所有 Type 参数实际上都是 RuntimeType 对象,您可以按照另一个答案中的建议查找基类。但是,如果您收到的类型不是 RuntimeType,则会收到一些“误报”。
You don't have to ToString() it; you should be able to access its Name through GetType() (which is pretty much the same thing). Either way, because it's a private class and not accessible from developer code, I think you're stuck with a "magic string" if you need to verify that it is specifically a RuntimeType. Not all "best solutions" are as elegant as we'd like.
If all Type parameters you'd get are actually RuntimeType objects, you can look for the base class as was suggested in another answer. However, if you can receive a Type that isn't a RuntimeType, you'll get some "false positives".