[英]C# Generics with Lists
I have these multiple versions of these two classes:我有这两个类的多个版本:
public class Contests : List<Contest> { }
public class Contest {
// stuff specific to Contest;
public Contests parent;
public void Attach() {
parent.Add(this);
}
}
And here's another:这是另一个:
public class Transactions : List<Transaction> { }
public class Transaction {
// stuff specific to Transaction;
public Transactions parent;
public void Attach() {
parent.Add(this);
}
}
So that I don't repeat code, can I take out the Attach into a base class using generics?为了不重复代码,我可以使用泛型将 Attach 取出到基类中吗?
public class MBData<T> {
public T parent;
public void Attach() {
T.Add(this);
}
}
I tried with the following but I receive an error about not being able to convert between Contests
and MBDatas<MBData<Contests>>
.我试着用下面的,但我收到有关不能够转换之间的误差
Contests
和MBDatas<MBData<Contests>>
。
public class MBDatas<S> : List<S> { }
public class MBData<B> where B : MBDatas<MBData<B>> { }
public class Contests : MBDatas<Contest> { }
public class Contest : MBData<Contests> { }
Does this work for you?这对你有用吗?
public abstract class MBData<P, C>
where P : MBDatas<P, C>
where C : MBData<P, C>
{
public void Attach()
{
this.Parent.Add((C)(object)this);
}
public P Parent { get; set; }
}
public abstract class MBDatas<P, C> : List<C>
where P : MBDatas<P, C>
where C : MBData<P, C>
{ }
You are forced to do a nasty double cast (C)(object)this
to get the Attach
method to work and this is the only rub with this approach.你被迫做一个讨厌的双重转换
(C)(object)this
来让Attach
方法工作,这是这种方法的唯一问题。 It works, but you need to be careful that you define the child classes properly.它有效,但您需要注意正确定义子类。
You can define your classes like this:你可以这样定义你的类:
public class Contests : MBDatas<Contests, Contest> { }
public class Contest : MBData<Contests, Contest> { }
public class Transactions : MBDatas<Transactions, Transaction> { }
public class Transaction : MBData<Transactions, Transaction> { }
And finally, use them like this:最后,像这样使用它们:
var cs = new Contests();
var c1 = new Contest() { Parent = cs };
var c2 = new Contest() { Parent = cs };
cs.Add(c1);
cs.Add(c2);
var ts = new Transactions();
var t1 = new Transaction() { Parent = ts };
var t2 = new Transaction() { Parent = ts };
ts.Add(t1);
ts.Add(t2);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.