如何设置泛型类的基类属性

时间:2016-02-21 14:58:38

标签: c# generics

我有一个基类:

.then

然后是一个传递了一个Generic类的类,该类传递了一个继承自MyBaseClass的( "<NSLayoutConstraint:0x7ffa58c20680 UIImageView:0x7ffa58c1fe50.top == UILabel:0x7ffa588c9660'Nguy\U00ean Tuyen'.top>", "<NSLayoutConstraint:0x7ffa58c20720 UILabel:0x7ffa588c9660'Nguy\U00ean Tuyen'.top == UITableViewCellContentView:0x7ffa588c94e0.topMargin>", "<NSLayoutConstraint:0x7ffa58c20950 V:[UIImageView:0x7ffa58c1fe50]-(16)-[UIWebView:0x7ffa588c9ee0]>", "<NSLayoutConstraint:0x7ffa58c20a90 V:[UIWebView:0x7ffa588c9ee0]-(NSSpace(8))-[UILabel:0x7ffa588c99d0'1 Tr\U1ea3 l\U1eddi']>", "<NSLayoutConstraint:0x7ffa58c20ae0 UILabel:0x7ffa588c99d0'1 Tr\U1ea3 l\U1eddi'.bottom == UITableViewCellContentView:0x7ffa588c94e0.bottomMargin + 5>", "<NSLayoutConstraint:0x7ffa58c295b0 'UIView-Encapsulated-Layout-Height' V:[UITableViewCellContentView:0x7ffa588c94e0(0.5)]>"

public abstract class MyBaseClass
{
    public string  MyProperty { get; set; } 
}

这就像我想要的那样。但是,只要我尝试设置基类属性,我就会收到编译错误:

  

对象不包含MyProperty的定义   在线

TViewModel

如何设置属性?

1 个答案:

答案 0 :(得分:6)

使用通用Activator.CreateInstance<T>代替:

public virtual async Task<IActionResult> Index()
{
    TViewModel viewModel = Activator.CreateInstance<TViewModel>();
    viewModel.MyProperty="test";
    return View(viewModel);
}

替代方法也可以是通过TViewModel : MyBaseClass, new()约束泛型类型参数(这可以节省反射开销)以包含默认构造函数,然后:

public virtual async Task<IActionResult> Index()
{
    TViewModel viewModel = new TViewModel();
    viewModel.MyProperty="test";
    return View(viewModel);
}