问题
I did not find the answer in searching for it.
I need a List that contains different classes, each of them inherent from a base class BaseA
, but each of them will have properties others will not have, or some that uses the same class will.
public class BaseA
{
public int ID = 0;
}
public class AA : BaseA
{
public int AID = 0;
}
public class AB : BaseA
{
public int BID = 1;
}
public class AC : BaseA
{
public int CID = 0;
}
Now the question is how do I get a single List that may contain class AA,AB and AC and the editor will not think i'm only working with one of them.
I tried to made the List<BaseA>
, but this will only expose the bassA properties, and what i need is like to be able to do List[0].AID
where it will understand what AID means if i'm talking about the AA class.
I may be going it all wrong, can someone point me to the right direction?
回答1:
You can try using Linq for this:
List<BaseA> list = ...
var result = list
.OfType<AA>() // Filter out AA instances only
.ElementAt(0) // or just First();
.AID;
回答2:
Are you looking for casting, perhaps?
var list = new List<BaseA>
{
new AA(),
new AB(),
new AC(),
}
var aa = list[0] as AA;
if (aa != null)
{
var id = aa.AID;
}
回答3:
Would need to place a variable or property in the base class that stores what type it is then attempt a cast (List[0] as AA) and if it doesn't return null use the newly cast object to select the desired variable.
The real question is why do the derived classes need their own ID variable, especially if you are throwing them in a list based on said ID.
回答4:
There is a possible way to do this simply and elegantly. Provide an abstract method in your base class (or multiple of them):
public abstract void AID(parameters);
And in each of the classes override that method to do a particular thing related to that class.
Or you can take an alternative way; check for each object if it's the type of each of the classes:
if(obj is AA){
//do AA stuff
}
if(obj is AB){
//do AB stuff
}
if(obj is AC){
//do AC stuff
}
回答5:
Couple of ways you can try,
- going with your approach, cast the item in the list to
((AA)List[0]).AID
.
You should have some knowledge of the object that it belongs to AA
in order to access the property AID
on it.
if your requirement is limited to the usage that you've described then I would suggest that you have something in similar lines provided below
class BaseA
{
public string ObjectType { get; set; } //enum would be a good choice.
public int ID { get; set; }
(or)
public Dictionary<string,int> AllProperties { get; set; }
}
With this approach, you can check the type of the class and call appropriate property on it.
来源:https://stackoverflow.com/questions/38658539/c-sharp-list-of-different-classes