【问题标题】:c# mvc get generic type using reflectionc# mvc 使用反射获取泛型类型
【发布时间】:2016-12-05 17:38:14
【问题描述】:

目前正试图找到一种方法来获取泛型类型类的类型,但一直无法找到这样做的方法。我目前的工作方法如下:

public class CategoryConfiguration : EntityTypeConfiguration<Category>
    {
        public CategoryConfiguration()
        {
            ToTable("Categories");
            Property(c => c.Name).IsRequired().HasMaxLength(50);
        }
    }

我想将此方法更改为:

public class CategoryConfiguration : EntityTypeConfiguration<T>
    {
        public CategoryConfiguration()
        {
            ToTable(/*get string representation of 'T' here and pluralize*/);
            Property(c => c.Name).IsRequired().HasMaxLength(50);
        }
    }

【问题讨论】:

    标签: c# inheritance reflection


    【解决方案1】:

    我认为你可以做到:

    ToTable(typeOf(T).Name);
    

    关于复数请阅读this

    【讨论】:

    • 在 C#6.0 中可以使用 nameof(T)
    【解决方案2】:

    如果您想查看类名,请使用nameof(T)。或者,如果您想查看 T 类型的不同名称边界,您可以使用 AttributeDescription 例如(阅读此处:https://msdn.microsoft.com/ru-ru/library/system.componentmodel.descriptionattribute(v=vs.110).aspx),并获取它的值。

    例如:

    [Description("/*name, which you would like to see*/")]
    public class Category
    {
        /* your class realization */
    }
    

    CategoryConfiguration 中使用

    ToTable((typeof(T).GetCustomAttributes(typeof(DescriptionAttribute), true)
                      .First() as DescriptionAttribute)
                      .Description);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多