我遇到了一个问题,我需要知道一个属性是否放置在一个类的属性上,但我受到限制,因为实际上我得到的只是该属性的一个实例(类型在这种情况下没有用)。
问题来自这样一个事实,即我正在使用自定义 ContractResolver 来检测此类属性,但在使用 ShouldSerialize 谓词的情况下,您从 DefaultContractResolver 获得的只是类型或实例。
我不能使用 Attribute.GetCustomAttributes(type) 因为该属性不在类型上。TypeDescriptor 也没有运气。我在想是否有可能从该实例获取成员信息,以便我可以将其传递给 GetCustomAttributes,这是否可能?你看有没有别的办法?
顺便说一句,我想要完成的是在某些属性上放置一个标记属性,以便我的合同解析器只能序列化该类型的某些属性,而不是所有这些属性。我不想把它放在类型本身上,因为有时我想序列化整个对象。为每种类型创建一个合约解析器也是不切实际的,因为这将是巨大的。
var instance = new MyClass();
instance.MyProperty = new OtherClass();
// propertyValue is all I get when I'm on the ShouldSerializeMethod
object propertyInstance = instance.MyProperty;
var attributes = Attribute.GetCustomAttributes(propertyInstance.GetType());
// this returns no attributes since the attribute is not on the type but on the property of another type
Console.WriteLine (attributes.Length);
public class MyClass
{
[MyCustomAttribute]
public OtherClass MyProperty { get; set; }
}
public class OtherClass
{
public string Name { get; set; }
}
public class MyCustomAttribute : Attribute
{
}