gpt4 book ai didi

c# - 使用 C#- DisplayFormatAttribute 中的属性格式化字段?

转载 作者:行者123 更新时间:2023-11-30 12:33:28 26 4
gpt4 key购买 nike

我正在寻找一种自动格式化实体中数据字段的有效方法 - 最好使用属性。

我们需要从数据模型生成一个 PDF 文件。我们希望确保可交付成果的一致性,因此我们希望将一些格式规则应用于某些数据字段(日期、电话号码、邮政编码等)。当然,我可以编写自定义属性和格式化代码,但我不想重新发明轮子。我看到很多使用 DataAnnotations 的 promise (尤其是 DisplayFormat 属性),但我似乎找不到任何使用这些属性的内置类。

我如何在非 UI(即非 MVC)上下文中执行此操作?

这是我们正在寻找的示例:

public class MyDataModel
{
[PhoneNumber]
public string PhoneNumber { get; set; }

public void FormatData()
{
//Invoke some .NET or other method changes the value of PhoneNumber into a desired format, i.e. (888)555-1234 based on its decorations.
}
}

我也对创建数据“ View ”而不是更新原始对象的解决方案持开放态度,即:

MyDataModel formatted = original.FormatData();

任何需要最少代码量的东西都是理想的。

最佳答案

您必须使用反射来读取类型的属性。 This answer提供了一些应该有帮助的扩展方法。这是一个 MVC 问题,但它也可以在 MVC 之外工作:


public static T GetAttribute<T>(this MemberInfo member, bool isRequired)
where T : Attribute
{
var attribute = member.GetCustomAttributes(typeof(T), false).SingleOrDefault();

if (attribute == null && isRequired)
{
throw new ArgumentException(
string.Format(
CultureInfo.InvariantCulture,
"The {0} attribute must be defined on member {1}",
typeof(T).Name,
member.Name));
}

return (T)attribute;
}

public static string GetPropertyDisplayName<T>(Expression<Func<T, object>> propertyExpression)
{
var memberInfo = GetPropertyInformation(propertyExpression.Body);
if (memberInfo == null)
{
throw new ArgumentException(
"No property reference expression was found.",
"propertyExpression");
}

var attr = memberInfo.GetAttribute<DisplayNameAttribute>(false);
if (attr == null)
{
return memberInfo.Name;
}

return attr.DisplayName;
}

public static MemberInfo GetPropertyInformation(Expression propertyExpression)
{
Debug.Assert(propertyExpression != null, "propertyExpression != null");
MemberExpression memberExpr = propertyExpression as MemberExpression;
if (memberExpr == null)
{
UnaryExpression unaryExpr = propertyExpression as UnaryExpression;
if (unaryExpr != null && unaryExpr.NodeType == ExpressionType.Convert)
{
memberExpr = unaryExpr.Operand as MemberExpression;
}
}

if (memberExpr != null && memberExpr.Member.MemberType == MemberTypes.Property)
{
return memberExpr.Member;
}

return null;
}

用法是:

string displayName = ReflectionExtensions.GetPropertyDisplayName<SomeClass>(i => i.SomeProperty);

关于c# - 使用 C#- DisplayFormatAttribute 中的属性格式化字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9265021/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com