Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
116 views
in Technique[技术] by (71.8m points)

c# - Polymorphism with .NET MVC model objects

I derive a bunch of models from a base model class. Here is an example of one such child model:

namespace MyProject.Models
{
    public abstract class Parent1 {}
}

namespace MyProject.Models
{
    public class Child1: Parent1  { ... }
}

Each of these models has pretty consistent functionality, which I code in separate classes I call "handlers." There is a base handler, to define the method names:

namespace MyProject.Models
{
    public abstract class Parent1Handler
    {
        public abstract void Update(Parent1 model);
    }
}

But when I try to create a derived handler, .NET is unhappy with my parameter type:

namespace MyProject.Models
{
    public class Child1Handler: Parent1Handler
    {
        public override void Update(Child1 model) { ... }
    }
}

It essentially demands that I use an argument of type Parent1 to override my method. But Child1 is derived from Parent1; shouldn't an argument of type Child1 be a suitable stand-in?

question from:https://stackoverflow.com/questions/65891561/polymorphism-with-net-mvc-model-objects

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As commenters have noted, that's not how overriding works. You can't change the signature of an overridden method at all. You could pass an instance of Child1 into your overridden Update method, but you can't change the signature.

To get at what it seems like you want to do, you'll have to leverage generics

public class Parent1Handler<TChild> where TChild : Parent1
{
    public abstract void Update(TChild model);
}
public class Child1Handler: Parent1Handler<Child1>
{
    public override void Update(Child1 model) 
    {
     ....
    }
}

This allows you to have a separate child Handler for each inherited model. However, I would check yourself and make sure that this is really what you want to be doing. Model inheritance can be a trap. It can facilitate code reuse, but it can also quickly lead to nightmares where it's difficult to figure out where specific pieces of logic are. If you are going to inherit models, I'd strongly encourage you not to go more than one layer deep.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...