开发者

How can I implement an interface that can take many object types

excuse what seems like a real noobie question but how can I implement the following

public interface IViewModel    {
        void Map<T>();
    }


  public class CarViewModel : IViewModel
    {
        public string Color { get; private set; }
        public int Tyres { get; private set; }

public CarViewModel(Car _car)

    }

//this is where the problem is - there can be many differnt kind of object but I want them all to implement a Map function. I want to be able to assign the properties to incomi开发者_Python百科ng object. I also need to cater for IList of cars coming in that need to be populated. I suspect I am not using Generics properly

public void Map<T>(Car _car){
Color = _car.Color;
Tyres = _car.Tyres;
} 


Do you mean this?

public interface IViewModel<T>
{
    void Map(T domainObject);
}

public class CarViewModel : IViewModel<Car>
{
    public Map(Car domainObject) { ... }
}


You say:

I suspect I am not using Generics properly

and you are correct. Additionally, you are not using polymorphism properly.

If you want to polymorphically accept several different types that all have something in common, then you need to create an interface that is the parent type of all of the types you will be using. You can do this without using any Generics at all.

What Generics (aka parametric polymorphism) gives you is a way to create one type that is parameterized by another type (and thus behaves like many different types). For example, IList<T> is parameterized by a type variable T -- then IList<string> and IList<int> are two separate types (with many possible subtypes each), but you only have to write the code once.

What are your actual requirements for this design? What are your ViewModel classes trying to accomplish?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜