【发布时间】:2022-01-13 05:25:06
【问题描述】:
有人可以帮我为 newtonsoft.json 和 mongodb 的自定义属性创建扩展方法吗?
假设我有以下课程:
public class Foo
{
[BsonElement("MyCustomDbName")]
[JsonProperty("MyCustomJsonName")]
public string Name { get; set; }
}
如何创建扩展方法来获取以下内容:
var myFoo = new Foo(){Name=""};
var mongoDbElementName = myFoo.Name.GetMongoDbElementName(); // should return 'MyCustomDbName'
var jsonPropertyName = myFoo.Name.GetJsonPropertyName(); // should return 'MyCustomJsonName'
或直接使用类本身:
var mongoDbElementName = Foo.Name.GetMongoDbElementName(); // should return 'MyCustomDbName'
var jsonPropertyName = Foo.Name.GetJsonPropertyName(); // should return 'MyCustomJsonName'
我试过这样的东西:
public static string GetMongoDbElementName(this Type modelType, PropertyInfo property)
{
return (modelType.GetProperty(nameof(property)) ?? throw new InvalidOperationException()).GetCustomAttribute<BsonElementAttribute>()?.ElementName;
}
但是有没有办法不带参数呢?
提前谢谢
【问题讨论】: