对于get属性DisplayName属性值,ModelMetadataProvider用于.NET框架版本。
ModelMetadataProviders.Current.GetMetadataForProperty(null, ClassType, PropertyName).DisplayName;我试着在.NET 6中获得.NET 6:
class SampleClass{
[Display(Name = "FirstName", ResourceType = typeof(MyResource))]
public string Name{ get; set; }
}
Type ClassType = typeof(SampleClass);
string PropertyName = "Name";
string displayName = TypeDescriptor.GetProperties(ClassType)
.Cast<PropertyDescriptor>()
.ToDictionary(p => p.Name, p => p.DisplayName)
.FirstOrDefault(p => p.Key == PropertyName).ToString(); DisplayName值将被接收,但是当CultureInfo被更改时,输出值不会改变!
发布于 2022-09-13 11:04:19
使用下面的代码,可以访问DisplayName值(它有一个资源),而无需使用ModelMetadataProvider和依赖项注入,而且它还可以通过更改语言来工作。
class SampleClass{
[Display(Name = "FirstName", ResourceType = typeof(MyResource))]
public string Name{ get; set; }
}
Type ClassType = typeof(SampleClass);
string PropertyName = "Name";
string displayName = "";
MemberInfo property = ModelType.GetProperty(Property);
displayName = property.GetCustomAttribute<DisplayAttribute>()?.GetName();https://stackoverflow.com/questions/73701104
复制相似问题