C# 确定集合所属的属性
我创建了一个小测试。在void Add(T)中使用反射时,我如何找出集合属于什么属性?我想通过编程方式获取属性名“MyVoces”,可能是通过PropertyInfoC# 确定集合所属的属性,c#,observablecollection,.net-4.8,C#,Observablecollection,.net 4.8,我创建了一个小测试。在void Add(T)中使用反射时,我如何找出集合属于什么属性?我想通过编程方式获取属性名“MyVoces”,可能是通过PropertyInfo void Main() { var myClass = new MyClass(); myClass.MyVotes.Add("Democratic"); myClass.MyVotes.Add("Republican"); myClass.MyVotes.A
void Main()
{
var myClass = new MyClass();
myClass.MyVotes.Add("Democratic");
myClass.MyVotes.Add("Republican");
myClass.MyVotes.Add("Independent");
}
public class MyClass
{
public MyCollection<string> MyVotes { get; }
public MyClass()
{
MyVotes = new MyCollection<string>();
}
}
public class MyCollection<T> : ObservableCollection<T>
{
public new void Add(T t)
{
base.Add(t);
// how do I find out what property name this collection is within MyClass object?
}
}
void Main()
{
var myClass=新的myClass();
myClass.MyVoces.Add(“民主党”);
myClass.MyVoces.Add(“共和党”);
myClass.MyVoces.Add(“独立”);
}
公共类MyClass
{
公共MyCollection MyVoces{get;}
公共MyClass()
{
MyVotes=新的MyCollection();
}
}
公共类MyCollection:ObservableCollection
{
公共新的无效添加(T)
{
添加(t);
//如何找出MyClass对象中此集合的属性名称?
}
}
看起来您可以完全控制源代码,因此我建议您只需通过构造函数参数将所需信息传递到集合中即可
public class MyClass
{
public MyCollection<string> MyVotes { get; }
public MyClass()
{
MyVotes = new MyCollection<string>(nameof(MyVotes));
}
}
public class MyCollection<T> : ObservableCollection<T>
{
private readonly string _propertyName;
public MyCollection(string propertyName) => _propertyName = propertyName
public new void Add(T t)
{
base.Add(t);
Console.WriteLine($"Using {_propertyName}");
}
}
公共类MyClass
{
公共MyCollection MyVoces{get;}
公共MyClass()
{
MyVoces=新的MyCollection(名称(MyVoces));
}
}
公共类MyCollection:ObservableCollection
{
私有只读字符串_propertyName;
public MyCollection(字符串propertyName)=>\u propertyName=propertyName
公共新的无效添加(T)
{
添加(t);
WriteLine($“使用{u propertyName}”);
}
}
我在这里使用了
nameof
,以确保重构安全。如果您需要传递的不仅仅是属性名称,例如PropertyInfo
,您可以这样做。没有。如果你把它叫做变量呢?调用方不应该关心调用其参数的值。你为什么想知道?这看起来有点难看而且是个坏主意。你想达到什么目标?应该有一个更合适的解决方案。我试图简化一个收集处理程序,当一个条目出现时,它调用AutoMapper并将其转储到另一个列表中。我可以通过在类中提供更多的编译时类型来解决这个问题,只是认为可能有一个更简单的方法。这是一个可观察的集合,对吗?所以要观察它。如果在将项添加到集合时需要MyClass执行某些操作,只需让它处理集合的CollectionChanged事件即可。集合本身不需要知道它在哪里被使用。