inheritance Problems with undefined types

2019-09-15 03:30发布

问题:

I want to be able to create a constructor that can call on its types but without any constraints.

public class Box
{
    public class Command
    {
        public string name;
        public string num;

        public Object PARAMS { get; set; }//<--- HERE
    }
}

I want PARAMS to be an undefined type that could possibly call one of these other classes

public class Person:Box
{
    public string LastName { get; set; }
    public string FirstName { get; set; }
}

or

 public class Item:Box
 {
     public string ItemName { get; set; }
     public string Info { get; set; }
 }

How can I define PARAMS? I am trying inheritance, but I am not so sure on how to call on other classes.

回答1:

You have two options - either set it's type as a Box, or make it generic:

public class Command<T> where T : Box
{
    public string name;
    public string num;

    public T PARAMS { get; set; }
}

Or:

public class Command
{
    public string name;
    public string num;

    public Box PARAMS { get; set; }
}