[英]How to create a List<I> containing instances of B, given instances of A (A derives from B and B implements I)?
See the following sample code. 请参见以下示例代码。
public interface I
{
int ID { get; set; }
}
public class B : I
{
public int ID { get; set; }
public string PropB { get; set; }
}
public class A : B
{
public string PropA { get; set; }
public IEnumerable<I> GetListOfBase()
{
// Attempt #1
var list1 = new List<I>();
B b1 = this as B;
list1.Add(b1);
// Attempt #2
var list2 = new List<I>();
B b2 = (B)this.MemberwiseClone();
list2.Add(b2);
return list1;
}
}
private static void TestGetListOfBase()
{
var a = new A() { ID = 1, PropA = "aaa", PropB = "bbb" };
var list = a.GetListOfBase();
}
In both my attempts, the list contains instances of A. I need it to contain instances of B. I am trying to avoid creating a new B, then copying the properties of A to B (I assume that will work!). 在我的两次尝试中,列表都包含A的实例。我需要它包含B的实例。我试图避免创建新的B,然后将A的属性复制到B(我认为这会起作用!)。
EDIT: the reason I need a list of Bs is that later on each B is passed into NPoco (a .NET micro ORM, derived from PetaPoco). 编辑:我需要一个B列表的原因是以后每个B都传递给NPoco(从PetaPoco派生的.NET微型ORM)。 NPoco takes the name of the type and uses it to determine the DB table to map to. NPoco接受类型的名称,并使用它来确定要映射到的数据库表。 Therefore it is critically important that a variable of the correct type is passed to the method. 因此,将正确类型的变量传递给该方法至关重要。
No, there is no way to "convert" instance of derived class to instance of base class. 不,没有办法将派生类的实例“转换”为基类的实例。 You have to create new instances of base class and copy properties. 您必须创建基类的新实例并复制属性。
There are multiple ways of doing so including manually copy each property (works for small number of properties). 这样做的方法有多种,包括手动复制每个属性(适用于少量属性)。 This operation frequently it is called "mapping" (hopefully it will help with your search for tools). 该操作通常称为“映射”(希望它将有助于您搜索工具)。
Note if you are fine with just having different type for list Enumerable.OfType<T>()
or Enumerable.Cast<T>()
followed by ToList()
would solve it in single statement. 请注意,如果只为列表Enumerable.OfType<T>()
或Enumerable.Cast<T>()
后跟ToList()
使用不同的类型就可以在单个语句中解决它。
You can use a copy constructor
to easily create instances of type B given an instance of type A (or anything that is assignable to B): 给定类型A的实例(或可分配给B的任何对象),可以使用copy constructor
轻松创建类型B的实例:
public class B : I
{
public int ID { get; set; }
public string PropB { get; set; }
public B(source B)
{
// copy values
this.ID = source.ID;
this.PropB = source.PropB;
}
}
You can call it like this: 您可以这样称呼它:
A instanceOfA = new A();
B instanceOfB = new B(instanceOfA);
// typeof(instanceOfB) == B
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.