作者:风行汽车-赣州景通4S店 | 来源:互联网 | 2023-08-13 11:18
To cut a long story short I have a C# function that performs a task on a given Type that is passed in as an Object instance. All works fine when a class instance is passed in. However, when the object is declared as an interface I'd really like to find the concrete class and perform the action upon that class type.
简而言之,我有一个C#函数,它对作为Object实例传入的给定Type执行任务。传入类实例时,一切正常。但是,当对象被声明为接口时,我真的很想找到具体的类并对该类类型执行操作。
Here is the ubiquitous bad example (resplendent with incorrect property casing etc):
这是无处不在的坏例子(金属外壳不正确等等):
public interface IA
{
int a { get; set; }
}
public class B : IA
{
public int a { get; set; }
public int b { get; set; }
}
public class C : IA
{
public int a { get; set; }
public int c { get; set; }
}
// snip
IA myBObject = new B();
PerformAction(myBObject);
IA myCObject = new C();
PerformAction(myCObject);
// snip
void PerformAction(object myObject)
{
Type objectType = myObject.GetType(); // Here is where I get typeof(IA)
if ( objectType.IsInterface )
{
// I want to determine the actual Concrete Type, i.e. either B or C
// objectType = DetermineConcreteType(objectType);
}
// snip - other actions on objectType
}
I'd like the code in PerformAction to use Reflection against it's parameter and see that it's not just an instance of IA but that it's an instance of B and to see the property "b" via GetProperties(). If I use .GetType() I get the Type of IA - not what I want.
我希望PerformAction中的代码使用Reflection来反对它的参数,看看它不仅仅是IA的一个实例,而是它的B实例,并通过GetProperties()查看属性“b”。如果我使用.GetType(),我会得到IA的类型 - 而不是我想要的。
How can PerformAction determine the underlying Concrete Type of the instance of IA?
PerformAction如何确定IA实例的基础Concrete Type?
Some might be tempted to suggest using an Abstract class but that is just the limitation of my bad example. The variable will be originally declared as an interface instance.
有些人可能会建议使用Abstract类,但这只是我的坏例子的限制。该变量最初将被声明为接口实例。
5 个解决方案