【发布时间】:2018-07-02 22:07:37
【问题描述】:
我有一个扩展 BaseModel 类的模型类。
public abstract class BaseModel {
public abstract string Name;
public abstract string NamePlural;
//....
}
public class Production : BaseModel
{
public string Name = "production";
public string NamePlural = "productions";
//....
}
我在其他地方调用了另一个使用 BaseModel 作为泛型基础的类:
public class Store {
public BaseModel SomeMethod<T>()
where T : BaseModel
{
// here I need to get the Name property and the NamePlural property
T.NamePlural; // gives compile error "T Not valid in the given context
// next try:
var model = typeof(T);
model.NamePlural; // simply doesn't exist (model.Name gives the name of the class, but not the property)
// another strange try:
BaseModel model = new T(); // haha....nope
//....
return something...;
}
}
//usage:
Store store = new Store();
Production p = SomeMethod<Production>();
所以问题是:
有没有一种简单的方法可以访问这些属性?
我什至尝试通过Assembly.GetTypes()..., ...
或者我需要 another 这些答案中描述的流派类: How to access Property of generic member in generic class?
是的,我已阅读相关问题 Access to properties of generic object 和Get property of generic class
【问题讨论】:
-
“获取 Name 属性”是什么意思 - 您是指 PropertyInfo 反射元数据吗?有没有对象实例传入方法? ...
-
“获取
NamePlural属性”到底是什么意思?你需要用它做什么? -
1) 你的子类属性不是
override,所以它没有按照你的想法做。 2)Name和NamePlural应该是静态的吗?你没有对象可以工作,所以很混乱。请创建一个minimal reproducible example。 -
假设你的代码不需要是泛型的,你会怎么写呢?正如另一条评论中提到的,您要在其上调用方法的类型 T 的对象在哪里?
-
字段不能是抽象的。
T是一个类型,而不是一个对象。您需要一个对象来访问非静态成员。