是否可以在不使用 MVC 的情况下访问 DisplayName 属性?
我已经使用 lambda 表达式为 List 重构了一个通用 CSV 构建器来访问正确的值,
public static string ToCsv<TModel>(this List<TModel> list, string delimiter, string lineBreak, string valueWrap, params Expression<Func<TModel, object>>[] expressions)
{
var sb = new StringBuilder();
var headers = expressions.Select(m => String.Format("{0}{1}{0}", valueWrap, GetPropertyName(m))).ToArray();
sb.Append(String.Format("{0}{1}", String.Join(delimiter, headers), lineBreak));
foreach (var listItem in list)
{
var values = expressions.Select(m => String.Format("{0}{1}{0}", valueWrap, m.Compile()(listItem))).ToArray();
sb.Append(String.Format("{0}{1}", String.Join(delimiter, values), lineBreak));
}
return sb.ToString();
}
但是这效果很好,因为我试图将其移动到跨多个服务器的多个项目的一些通用代码中以供访问。我无法引用 System.Web.Mvc 程序集
是否有一个好的方法来访问 DisplayName 属性,如果该属性不存在,则访问变量名称?
我当前尝试访问 ((MemberExpression) expression.Body).Member.Name
但是,如果必须将值转换为字符串,它将不起作用。 (即传递 int 并隐式转换)
第二次尝试迭代属性对内部类不起作用(即 model
=> model.innerClass.property
)
I have refactored out a generic CSV builder for List using lambda expressions to access the correct values
public static string ToCsv<TModel>(this List<TModel> list, string delimiter, string lineBreak, string valueWrap, params Expression<Func<TModel, object>>[] expressions)
{
var sb = new StringBuilder();
var headers = expressions.Select(m => String.Format("{0}{1}{0}", valueWrap, GetPropertyName(m))).ToArray();
sb.Append(String.Format("{0}{1}", String.Join(delimiter, headers), lineBreak));
foreach (var listItem in list)
{
var values = expressions.Select(m => String.Format("{0}{1}{0}", valueWrap, m.Compile()(listItem))).ToArray();
sb.Append(String.Format("{0}{1}", String.Join(delimiter, values), lineBreak));
}
return sb.ToString();
}
This works well, however because I am trying to move this into some common code for several projects across several servers to access. I cannot reference the System.Web.Mvc
assembly
Is there a good way to access the DisplayName
Attribute and if that doesnot exist, access the variable name?
My current attempt access the ((MemberExpression) expression.Body).Member.Name
however it will not work if it has to convert a value to string. (ie passing an int and implicitly converting)
A second attempt of iterating over the attributes did not work for inner class (ie model
=> model.innerClass.property
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
通过几个简单的辅助函数,您可以消除对 System.Web.Mvc 程序集的所有引用。您还会在下面的示例中注意到 (model => model.member.property) 的工作原理。
With a couple simple helper functions, you can eliminate all reference to the System.Web.Mvc assembly. You'll also notice in the example below that (model => model.member.property) works.