我有三个类:SomeThing,SomeOtherThing和YetAntherThing.这三个都有一个名为Properties的相同成员.在每个类中,它是一个键/值对,因此我可以引用obj1.Name,obj1.Value,obj2.Name,obj2.Value,obj3.Name和obj3.Value.我想将这三个对象传递给一个方法,该方法可以遍历各自的"属性"集合,而无需在编译时知道它正在进行哪些操作.我想象的是:
SomeThing obj1;
SomeOtherThing obj2;
YetAntherThing obj3;
DoProperties( obj1, obj1.GetType() );
DoProperties( obj2, obj2.GetType() );
DoProperties( obj3, obj3.GetType() );
...
private void DoProperties( object obj, Type objectType )
{
// this is where I get lost. I want to "cast" 'obj' to the type
// held in 'objectType' so that I can do something like:
//
// foreach ( var prop in obj.Properties )
// {
// string name = prop.Name;
// string value = prop.Value;
// }
}
Run Code Online (Sandbox Code Playgroud)
注意:SomeThing,SomeOtherThing和YetAntherThing类是在外部定义的,我无法控制它们或访问它们的源代码,它们都是密封的.
你有两个选择; 或者让每个类实现一个暴露集合的接口,例如:
interface IHasProperties
{
PropertyCollection Properties {get;}
}
Run Code Online (Sandbox Code Playgroud)
然后声明您的方法,引用该接口:
private void DoProperties(IHasProperties obj)
{
foreach (var prop in obj.Properties)
{
string name = prop.Name;
string value = prop.Value;
}
}
Run Code Online (Sandbox Code Playgroud)
或者使用反射在运行时查找Properties集合,例如:
private void DoProperties(object obj)
{
Type objectType = obj.GetType();
var propertyInfo = objectType.GetProperty("Properties", typeof(PropertyCollection));
PropertyCollection properties = (PropertyCollection)propertyInfo.GetValue(obj, null);
foreach (var prop in properties)
{
// string name = prop.Name;
// string value = prop.Value;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2819 次 |
| 最近记录: |