2016-12-05 94 views
0

當前試圖找到一種方法來獲取一般類型的類的類型,並且一直無法找到這樣做的方法。我的電流,工作方法如下所示:c#mvc使用反射獲得泛型類型

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); 
     } 
    } 

回答

6

我認爲你可以這樣做:

ToTable(typeOf(T).Name); 

關於多元化,請參閱this

+2

(T) – Ali7091

1

如果您想查看課程名稱,請使用nameof(T)。或者,如果您希望看到與T類型綁定的不同名稱,則可以使用Attribute,Description(例如,請閱讀: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在C#6.0,你可以使用nameof使用

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