【发布时间】:2015-09-30 18:14:06
【问题描述】:
我有以下问题:我想在第一步中为类Foo 的自动实现属性prop 添加一个属性。
在第二步中,我将遍历Foo 的所有字段并将值复制到这些字段(还找到并复制了自动实现的属性字段的值)。在这部分我需要访问属性的信息。
class FieldSetter
{
// This Method is called from outside and should work for any class
private void SetFieldValues(object unknownObject)
{
foreach (var field in
unknownObject.GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance |
BindingFlags.Static).Where((field) => !field.IsLiteral))
{
if (!EvalAttribute(Attribute.GetCustomAttributes(field))) // the Attribute should be accessed here
{
// Do something if no special Information is set
field.SetValue(a, "default Value");
}
else
{
// Do special things
field.SetValue(a, "special Value");
}
}
}
internal static bool EvalAttribute(Attribute[] attributes)
{
foreach (System.Attribute attr in attributes)
{
var myAttr = attr as MyAttribute;
if (myAttr != null)
{
if (myAttr.SomeAttributeValues == "Specific Attribute Value")
{
return true;
}
}
}
return false;
}
}
// This class is a example for how a given Object can look like
class Foo
{
[MyAttribute("Example Information")] // This Attribute won't be accessed via prop-Field
int prop { get; set; }
[MyAttribute("Another Example Information")] // This Attribute won't be accessed via prop-Field
int field;
//... lots of other fields and properties
}
[System.AttributeUsage(System.AttributeTargets.All)]
class MyAttribute : Attribute
{
public MyAttribute(string someInformation)
{
SomeAttributeValues = someInformation;
}
public string SomeAttributeValues;
}
【问题讨论】:
-
是否有理由需要遍历所有 字段 而不是遍历 properties?如果
prop不是自动属性,但有一些其他特殊实现,你会怎么做?有一种 hacky 方法可以完成您正在做的事情,但我建议您先探索直接访问属性设置器的可能性。 -
不知道类,由
SetFieldValues处理。所以 Foo 对我来说是一个“黑匣子”。另一种方法可能是,排除具有我迭代中的属性的字段。我想这样做的主要原因是:我有 2 个类似的对象。每个对象包含不同的信息(私有或公共原始字段,...,具有类的字段(它们也将被递归复制),...,来自自动属性的字段,...)。我想在 1 个实例中合并所有这些信息。 -
您发布的代码并没有明确说明您可以访问哪些信息,哪些信息不能访问。您的代码是否提供了程序集?类型列表?字段列表?属性列表?如果你的代码是
GetFields(),那么它可以很容易地说GetProperties(),对吧? -
你说得对,我可以额外使用
GetProperties(),但是我也必须从我的GetFields()迭代中排除相应的字段。否则,某些字段将使用 AND 而没有属性 Information 进行处理。 -
您确定要访问 private 字段?能够检测私有成员的自定义属性似乎是一个非常奇怪的要求。你不能只访问公共字段和属性吗?
标签: c# properties attributes field