【问题标题】:Get all properties of an implemented interface获取已实现接口的所有属性
【发布时间】:2017-08-31 21:36:04
【问题描述】:

我有以下设置:

public interface IInput
{
}

public class SomeInput : IInput
{
    public int Id { get; set; }
    public string Requester { get; set; }
}

现在我想编写一个函数,它可以接受任何实现 IInput 并使用反射来给我属性:

public Display(IInput input)
{
    foreach (var property in input.GetType().GetProperties())
    {
        Console.WriteLine($" {property.Name}: {property.GetValue(input)}");
    }
}

在哪里

var test = new SomeInput(){Id=1,Requester="test"};
Display(test);

表演

Id: 1
Requester: test

【问题讨论】:

  • 好的,你似乎已经给出了你想要的代码......那么问题是什么?
  • 他说了什么。但是您只需要对象的 IInput 属性值还是其所有属性的值?
  • 等等,这行得通吗?我认为反射只会显示接口的属性(IInput)而不是实现的属性(SomeInput)
  • .GetType() 将为您提供传入对象的实际具体类型。
  • @CuriousDeveloper 你已经在你的“节目”部分展示了它的工作原理。

标签: c# reflection interface


【解决方案1】:

如果你使用typeof(),你会得到变量的类型。但如果您使用GetType(),您将获得实际的运行时类型,您可以从中反映所有已实现的属性。

void DumpProperties(IInput o)
{
    var t = o.GetType();
    var props = t.GetProperties(BindingFlags.Instance | BindingFlags.Public);
    foreach (var prop in props)
    {
        Console.WriteLine(String.Format("Name: {0} Value: {1}",
            prop.Name,
            prop.GetValue(o).ToString()
        );
    }
}     

【讨论】:

    猜你喜欢
    • 2019-07-25
    • 1970-01-01
    • 2018-08-24
    • 1970-01-01
    • 2010-09-06
    • 1970-01-01
    • 2011-08-16
    • 1970-01-01
    相关资源
    最近更新 更多