Why can't my view's model bind with my generic ViewModel which implements an interface? (ASP.NET MVC 3)

前端 未结 2 1483
星月不相逢
星月不相逢 2021-01-18 07:06

I\'m trying to pass my View an instance of the following ViewModel:

public class CompanyListViewModel where T : ICompany
{
    public IEnumerable<         


        
相关标签:
2条回答
  • 2021-01-18 07:18

    What you're trying to accomplish should be possible by using an Interface for the ViewModel class and declaring the Generic type as Covariant. Like this:

    interface ICompanyListViewModel<out T> where T : ICompany
    {
    }
    

    That way you could also get away with an abstract class instead of an interface for Company.

    0 讨论(0)
  • 2021-01-18 07:32

    Consider that interfaces cannot provide implementations when you think about this situation and it should become apparent that you need to close your generic type with the specific interface you want the generic class to operate upon.

    If it's not apparent, well, consider further that from a pure OOP standpoint, interfaces can't define implementations, only classes can, and that C# doesn't allow you to specify overlapping interfaces.

    It sounds to me like you are trying to treat an interface like an abstract base class.

    0 讨论(0)
提交回复
热议问题