c# - 使用给定基类创建派生类

标签 c#

如果我有这个:

public class bClass
{
    int id {get; set;}
    string name {get; set;}
}

public class dClass : bClass
{
    int extraVal {get; set;}
}

我有一个 bClass 对象列表:

List<bClass> baseClassList = getBaseClassList();

将 baseClassList 转换为 dClass 对象列表(并将“extralVal”设置为指定值)的最简单方法是什么?我希望有一个类似的解决方案:

public class dClass : bClass
{
    public dClass(bClass b, int exVal)
    {
        base = b;
        extraVal = exVal;
    }
    int extraVal {get; set;}
}

List<dClass> dClassList = bClassList.ConvertAll(x => new dClass(x, exVal));

它本质上只是插入基础,然后设置额外的属性值,但显然这不是正确的语法。正确的做法是什么?

最佳答案

不确定具体情况,但预测可能会有所帮助?

bClassList.Select(i=>new dClass{ id=i.id, name=i.name, extraval=exVal});

或者你可以使用反射

public dClass(bClass c) 
{ 
// copy base class properties. 
 foreach (PropertyInfo prop in c.GetType().GetProperties()) 
 {   
  PropertyInfo prop2 = c.GetType().GetProperty(prop.Name); 
  prop2.SetValue(this,prop.GetValue(c, null), null); 
 }  
}

关于c# - 使用给定基类创建派生类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17290580/

相关文章:

c# - 在窗体关闭时关闭 SQL 连接 (C#)

C# - 将 List<JToken> 转换为 List<string> 单行

c# - IDX :20803 Unable to obtain configuration from. .. - Web API

c# - 如何使用每个选项卡的 PID 获取 Internet Explorer 选项卡的 URL?

c# - 如何使用 C# 从 Visual Studio 传递管道变量

c# - 如果子窗口处于事件状态,则防止关闭父窗口

c# - WPF 样式 : Can't change background of button?

c# - Breeze 导航属性未加载

c# - 如何在 Microsoft Bot Framework 的 LuisDialog 中获取 LUIS 上下文 ID

c# - 移除图片背景