是否可以在不使用 MVC 的情况下访问 DisplayName 属性?

发布于 2024-11-16 09:01:52 字数 1110 浏览 3 评论 0原文

我已经使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

裸钻 2024-11-23 09:01:52

通过几个简单的辅助函数,您可以消除对 System.Web.Mvc 程序集的所有引用。您还会在下面的示例中注意到 (model => model.member.property) 的工作原理。

using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Linq.Expressions;
using System.ComponentModel;
using System.Reflection;

namespace Test
{
    public class Program
    {
        public static void Main(string[] args)
        {
            List<Class1> foobars = new List<Class1>();
            foobars.Add(new Class1 { Foo = "Hello world!", Bar = -1, Skip = false, Ref = new Class2 { ToBe = true } });

            string result = foobars.ToCsv(",", Environment.NewLine, "\"", m => m.Foo, m => m.Bar, m => m.Ref.ToBe);
        }

        public class Class1
        {
            [DisplayName("Foo Property")]
            public string Foo { get; set; }

            public int Bar { get; set; }

            [DisplayName("Skipped Property")]
            public bool Skip { get; set; }

            [DisplayName("Reference")]
            public Class2 Ref { get; set; }
        }

        public class Class2
        {
            [DisplayName("To Be or Not To Be")]
            public bool ToBe { get; set; }
        }
    }

    public static class Extensions
    {
        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, GetDisplayName(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();
        }

        // Get DisplayName, otherwise fallback to Name
        private static string GetDisplayName(LambdaExpression memberReference)
        {
            MemberInfo info = GetMemberInfo(memberReference);
            DisplayNameAttribute displayNameAttr = Attribute.GetCustomAttribute(info, typeof(DisplayNameAttribute)) as DisplayNameAttribute;
            return (displayNameAttr != null ? displayNameAttr.DisplayName : info.Name);
        }

        // Can be swapped for your favourite GetMemberInfo/GetPropertyInfo utility method (there are many out there)
        // Source: http://blog.baltrinic.com/software-development/dotnet/extension-methods-for-converting-lambda-expression-to-strings
        private static MemberInfo GetMemberInfo(LambdaExpression memberReference)
        {
            MemberExpression memberExpression;
            var unary = memberReference.Body as UnaryExpression;
            if (unary != null)
                //In this case the return type of the property was not object,
                //so .Net wrapped the expression inside of a unary Convert()
                //expression that casts it to type object. In this case, the
                //Operand of the Convert expression has the original expression.
                memberExpression = unary.Operand as MemberExpression;
            else
                //when the property is of type object the body itself is the
                //correct expression
                memberExpression = memberReference.Body as MemberExpression;

            if (memberExpression == null || !(memberExpression.Member is MemberInfo))
                throw new ArgumentException("Expression was not of the form 'x => x.member'.");

            return memberExpression.Member;
        }
    }
}

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.

using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Linq.Expressions;
using System.ComponentModel;
using System.Reflection;

namespace Test
{
    public class Program
    {
        public static void Main(string[] args)
        {
            List<Class1> foobars = new List<Class1>();
            foobars.Add(new Class1 { Foo = "Hello world!", Bar = -1, Skip = false, Ref = new Class2 { ToBe = true } });

            string result = foobars.ToCsv(",", Environment.NewLine, "\"", m => m.Foo, m => m.Bar, m => m.Ref.ToBe);
        }

        public class Class1
        {
            [DisplayName("Foo Property")]
            public string Foo { get; set; }

            public int Bar { get; set; }

            [DisplayName("Skipped Property")]
            public bool Skip { get; set; }

            [DisplayName("Reference")]
            public Class2 Ref { get; set; }
        }

        public class Class2
        {
            [DisplayName("To Be or Not To Be")]
            public bool ToBe { get; set; }
        }
    }

    public static class Extensions
    {
        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, GetDisplayName(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();
        }

        // Get DisplayName, otherwise fallback to Name
        private static string GetDisplayName(LambdaExpression memberReference)
        {
            MemberInfo info = GetMemberInfo(memberReference);
            DisplayNameAttribute displayNameAttr = Attribute.GetCustomAttribute(info, typeof(DisplayNameAttribute)) as DisplayNameAttribute;
            return (displayNameAttr != null ? displayNameAttr.DisplayName : info.Name);
        }

        // Can be swapped for your favourite GetMemberInfo/GetPropertyInfo utility method (there are many out there)
        // Source: http://blog.baltrinic.com/software-development/dotnet/extension-methods-for-converting-lambda-expression-to-strings
        private static MemberInfo GetMemberInfo(LambdaExpression memberReference)
        {
            MemberExpression memberExpression;
            var unary = memberReference.Body as UnaryExpression;
            if (unary != null)
                //In this case the return type of the property was not object,
                //so .Net wrapped the expression inside of a unary Convert()
                //expression that casts it to type object. In this case, the
                //Operand of the Convert expression has the original expression.
                memberExpression = unary.Operand as MemberExpression;
            else
                //when the property is of type object the body itself is the
                //correct expression
                memberExpression = memberReference.Body as MemberExpression;

            if (memberExpression == null || !(memberExpression.Member is MemberInfo))
                throw new ArgumentException("Expression was not of the form 'x => x.member'.");

            return memberExpression.Member;
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文