c# - 查找接口(interface)实例背后的具体类型

标签 c# interface types concrete

长话短说,我有一个 C# 函数,它对作为对象实例传入的给定类型执行任务。当传入类实例时,一切正常。但是,当对象被声明为接口(interface)时,我真的很想找到具体的类并对该类类型执行操作。

这是一个普遍存在的错误示例(属性大小写不正确等):

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 实例的基础具体类型?

有些人可能会建议使用抽象类,但这只是我的错误示​​例的局限性。该变量最初将被声明为接口(interface)实例。

最佳答案

Type objectType = myObject.GetType();

根据你的例子,应该仍然给你具体的类型。

关于c# - 查找接口(interface)实例背后的具体类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1159906/

相关文章:

java - 为什么不使用 switch case 语句?

c# - 接口(interface)和共享实现

c# - Entity Framework : Extending partial class with interface without touching the EF-generated classes

Magento - 删除产品类型选项

c# - LINQ to SQL和SQLite-在UTF-8字符串中搜索

c# - 在 wpf 项目的 HttpClient 上使用 await

c# - 检测何时在 Windows 窗体的标题栏中按下帮助按钮?

sql - 将表列的数据类型从时间戳更改为 bigint

java - 我想在变量中存储 0 到 100 之间的数字 - 我应该使用 INT 还是 BYTE,为什么?

c# - 从进程 ID/对象获取进程实例名称(更快的方式)