2017-08-31 99 views
-1

我有以下设置:获得实现接口的所有属性

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 
+5

好的,所以你似乎已经给出了你想要的代码......那么这有什么问题? –

+0

他说什么。但是,你只想要对象的IInput属性或其所有属性的值? –

+0

等一下,这会起作用吗?我想反射只会显示接口的属性(IInput)而不是实现的属性(SomeInput) – CuriousDeveloper

回答

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() 
     ); 
    } 
}  
+0

这已经是什么OP –