我从很多地方读到接口(interface)中定义的属性 DO NOT 应用于实现类,并且会被忽略:
- Can a C# class inherit attributes from its interface?
- Attribute on Interface members does not work
- http://bradwilson.typepad.com/blog/2011/08/interface-attributes-class-attributes.html
但是,属性DO似乎适用于实现类:
using Newtonsoft.Json;
interface TestInterface
{
[JsonProperty(PropertyName = "foo")]
string id { get; set; }
}
class Test : TestInterface
{
public string id { get; set; }
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine(JsonConvert.SerializeObject(new Test()));
}
}
Console Output: {"foo": null}
在上面的示例中,JsonProperty 属性显然被应用在实现类中(将“id”字段名称更改为“foo”以进行序列化)。
接口(interface)中 C# 属性的行为是否发生了变化,还是我遗漏了什么?
最佳答案
属性是通过反射查询的,并且可以以开发人员想要的任何方式访问。为了在您的示例代码中证明这是如何工作的,我查看了 NewtonSoft.Json source看看它是如何加载这个值的。
它获取 JsonProperty
属性的方法是在 MemberInfo
上调用以下内容。
JsonTypeReflector.GetAttribute<JsonPropertyAttribute>(member)
可以看到这个问题时这个方法的来源here
正如您在 364-376 行中看到的那样,它遍历 MemberInfo
的接口(interface),如果无法从正在使用它的类加载 JsonProperty,则尝试从接口(interface)获取属性。
关于c# - 在 C# 中,接口(interface)中定义的属性是否适用于实现类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46800779/