[英]How do I access a certain field of 'object' without casting it to one type when it can be several types?
I have an object that can be assigned different classes, all of which have a Position
field which I need to access regardless of the object's type. 我有一个可以分配不同类的对象,所有这些类都有一个
Position
字段,无论对象的类型如何,我都需要访问该字段。 Visual Studio won't let me compile var pos = myObject.Position
because object
doesn't have a Position
field. Visual Studio不允许我编译
var pos = myObject.Position
因为object
没有Position
字段。 And I can't cast to MyClass
, because there can be several other classes assigned to that variable. 而且我无法转换为
MyClass
,因为可以为该变量分配其他几个类。
How do I access the Position
field without casting to one type? 如何在不转换为一种类型的情况下访问“
Position
字段?
The best option would be to make all of your classes implement a common interface, and then use that interface to access the properties. 最好的选择是使所有类都实现一个公共接口,然后使用该接口访问属性。
However, if these are classes outside of your control, there are other options. 但是,如果这些类超出了您的控制范围,则还有其他选择。 You could use Reflection to access the field/property (via Type.GetField and FieldInfo.GetValue , etc), though this is slow at runtime.
您可以使用Reflection访问字段/属性(通过Type.GetField和FieldInfo.GetValue等),尽管这在运行时很慢。
If you're using C# 4 or later, you can use dynamic
: 如果您使用的是C#4或更高版本,则可以使用
dynamic
:
dynamic theObject = yourObject;
Point position = theObject.Position;
This will use dynamic (runtime) binding to find the Position
property or field on your type. 这将使用动态(运行时)绑定来查找类型的
Position
属性或字段。
All of those different classes which have a Position
field should either inherit that field from a common base class, or get it (it would have to be a property then) from a common interface. 所有具有
Position
字段的所有不同类都应该从通用基类继承该字段,或者从通用接口中获取它(然后必须是一个属性)。
The interface solution might look like this: 接口解决方案可能如下所示:
interface IHasPosition
{
int Position { get; }
}
then all of the classes shall say : IHasPosition
, and your myObject
variable should be declared of type IHasPosition
in the code. 然后所有类都应该说
: IHasPosition
,并且您的myObject
变量应在代码中声明为IHasPosition
类型。
Once option is to make all of the different classes inherit from a class which defines Position
then when you get the object refer to it by the parent classes type and you can access the properties that are defined there without knowing the specific type. 一旦让所有不同的类都继承自定义
Position
的类,然后当您通过父类类型引用该对象时,就可以访问那里定义的属性,而无需知道具体的类型。
Keep in mind if they don't have much common functionality this may not be a very good approach. 请记住,如果它们没有太多通用功能,那么这可能不是一个很好的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.