这是无处不在的坏例子(典型的属性大小写不正确等):
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
}
我希望 PerformAction 中的代码对其参数使用反射,并查看它不仅是 IA 的实例,而且是 B 的实例,并通过 GetProperties() 查看属性“b”。如果我使用 .GetType() 我得到 IA 的类型 - 不是我想要的。
PerformAction 如何确定 IA 实例的底层具体类型?
有些人可能会建议使用抽象类,但这只是我的坏例子的局限性。该变量最初将被声明为接口实例。
Type objectType = myObject.GetType();
根据您的示例,仍然应该为您提供具体类型。
public interface IA
{
int a { get; set; }
void PerformAction();
}
public class B: IA
{
public int a { get; set; }
public int b { get; set; }
public void PerformAction()
{
// perform action specific to B
}
}
public class C : IA
{
public int a { get; set; }
public int c { get; set; }
public void PerformAction()
{
// perform action specific to C
}
}
void PerformActionOn(IA instance)
{
if (instance == null) throw new ArgumentNullException("instance");
instance.PerformAction();
// Do some other common work...
}
B b = new B();
C c = new C();
PerformActionOn(b);
PerformActionOn(c);
void PerformAction(object myObject)
{
B objectType = myObject as B; // Here is where I get typeof(IA)
if ( objectType != null )
{
//use objectType.b
}
else
{
//Same with A
}
// snip - other actions on objectType
}