简体   繁体   English

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

[英]How to set the base class property of a generic class

I have a base class: 我有一个基类:

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

and then a class that gets passed a Generic class that get passed a TViewModel that inherits from MyBaseClass 然后获取传递的是获得通过一个通用类的类TViewModel从MyBaseClass继承

public abstract class MyGenericController<TViewModel> : Controller
    where TViewModel :  MyBaseClass
{
    public virtual async Task<IActionResult> Index()
    {
        object viewModel = Activator.CreateInstance(typeof(TViewModel));
        viewModel.MyProperty="test";
        return View(viewModel);
    }
}

This works like I want it. 这就像我想要的那样。 However as soon as I try set the base class property I get a compile error: 但是,一旦我尝试设置基类属性,我得到一个编译错误:

object does not contain a definition for MyProperty on the line 对象不包含该行的MyProperty定义

viewModel.MyProperty="test";

How do I set the property? 我该如何设置属性?

Use the generic Activator.CreateInstance<T> instead: 请改用通用的Activator.CreateInstance<T>

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

An alternative can also be to constraint the generic type parameter (which saves you the overhead of reflection) to contain a default constructor via TViewModel : MyBaseClass, new() , and then: 另一种方法是约束泛型类型参数(这可以节省反射的开销),通过TViewModel : MyBaseClass, new()包含一个默认构造TViewModel : MyBaseClass, new() ,然后:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM