通过任何类的任何observablecollection,并获得方法中的属性 - C#

问题描述:

我有一个C#中的方法,我需要将ObservableCollection传递给thaat方法。我需要在类T中获取属性和它们的值。但是,我的类T可以是任何类名。通过任何类的任何observablecollection,并获得方法中的属性 - C#

例如为:

public class MyClass 
{ 
    public string prop1 {get; set;} 
    public prop2 {get; set; } 
} 

public class OtherClass 
{ 
    public string OtherProp1 {get; set;} 
    public OtherProp2 {get; set;} 
} 

private ObservableCollection<MyClass> _myselectedItems = new ObservableCollection<MyClass>(); 

public ObservableCollection<MyClass> MySelectedItems 
{ 
    get{return _myselectedItem;} 
    set{_myselectedItem = value;} 
} 

private ObservableCollection<OtherClass> _otherselectedItems = new ObservableCollection<OtherClass>(); 

public ObservableCollection<OtherClass> OtherSelectedItems 
{ 
    get{return _otherselectedItem;} 
    set{_otherselectedItem = value;} 
} 

public GenericMethod<T>(ObservableCollection<T> anySelectedItems) 
{ 
    if (anySelectedItems[0].**prop1** != "Hello") 
    { // do something 
    } 
} 

我有我想打电话给这个通用方法。

---->这里我希望能够根据调用此方法的位置以及anySelectedItems的类型获取该类的相应属性(例如prop1,prop2,otherProp1或OtherProp2)。如果传递值是ObservableCollection<MyClass>那么我需要得到prop1和prop2。

任何建议表示赞赏。 谢谢。

+0

[获取泛型类的属性]的可能重复(https://stackoverflow.com/questions/14129421/get-property-of-generic-class) –

+0

******注意:更正最后一句:如果传递的值是ObservableCollection 那么我需要获取prop1和prop2。 – Always23

+0

@ Kitty23不要在评论中纠正,编辑你的文章 – maccettura

根据我的评论,我会推荐一个apporach如下。让界面为你做好工作。

public interface IMyClass { 
    string prop1 {get; set;} 
    string prop2 {get; set;} 
} 

public class MyClass : IMyClass 
{ 
    public string prop1 {get; set;} 
    public string prop2 {get; set; } 
} 

public class OtherClass : IMyClass 
{ 
    public string prop1 {get; set;} 
    public string prop2 {get; set;} 
} 

private ObservableCollection<MyClass> _myselectedItems = new ObservableCollection<MyClass>(); 

public ObservableCollection<IMyClass> MySelectedItems 
{ 
    get{return _myselectedItem;} 
    set{_myselectedItem = value;} 
} 

private ObservableCollection<OtherClass> _otherselectedItems = new ObservableCollection<OtherClass>(); 

public ObservableCollection<OtherClass> OtherSelectedItems 
{ 
    get{return _otherselectedItem;} 
    set{_otherselectedItem = value;} 
} 

public GenericMethod(ObservableCollection<IMyClass> anySelectedItems) 
{ 
    if (anySelectedItems[0].prop1 != "Hello") 
    { // do something 
    } 
} 
+0

为什么你已经改变了公众的ObservableCollection MySelectedItems { 得到{_myselectedItem;} 集合{_myselectedItem =值;} }公众的ObservableCollection MySelectedItems { 得到{_myselectedItem;} 集合{_myselectedItem =值;} }将MyClass转换为IMyClass? – Always23

+0

因此,它对接口或类的描述而不是类本身起作用。这样,只要该类实现IMyClass接口,该方法就不会关心它给出的类。 –

我确实用prop1和prop2创建了一个类。我将该类的类型传递给ObservableCollections <>,然后创建该类的不同实例并将其传递到我的泛型方法中。