【问题标题】:Dynamically adding properties to an Object from an existing static object in C#从 C# 中的现有静态对象动态地将属性添加到对象
【发布时间】:2016-04-18 05:56:40
【问题描述】:

在我的 ASP .Net Web API 应用程序中进行数据库调用时,需要将一些属性添加到已经具有一些现有属性的模型类中。

我知道在这种情况下我可以使用ExpandoObject 并在运行时添加属性,但我想知道如何先从现有对象继承所有属性,然后再添加一些。

假设例如,传递给方法的对象是ConstituentNameInput,并被定义为

public class ConstituentNameInput
{
    public string RequestType { get; set; }
    public Int32 MasterID { get; set; }
    public string UserName { get; set; }
    public string ConstType { get; set; }
    public string Notes { get; set; }
    public int    CaseNumber { get; set; }
    public string FirstName { get; set; }
    public string MiddleName { get; set; }
    public string LastName { get; set; }
    public string PrefixName { get; set; }
    public string SuffixName { get; set; }
    public string NickName { get; set; }
    public string MaidenName { get; set; }
    public string FullName { get; set; }
}

现在我想在我动态创建的对象中添加所有这些现有属性,然后添加一些名为 wherePartClauseselectPartClause 的属性。

我该怎么做?

【问题讨论】:

  • 请谨慎使用格式 - 将整个非代码段落以代码形式放置是没有意义的。
  • 对不起..这是我的错。今后我会照顾好它。

标签: c# dynamic expandoobject


【解决方案1】:

你可以创建一个新的ExpandoObject 并使用反射来填充现有对象的属性:

using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Reflection;

class Program
{
    static void Main(string[] args)
    {
        var obj = new { Foo = "Fred", Bar = "Baz" };
        dynamic d = CreateExpandoFromObject(obj);
        d.Other = "Hello";
        Console.WriteLine(d.Foo);   // Copied
        Console.WriteLine(d.Other); // Newly added
    }

    static ExpandoObject CreateExpandoFromObject(object source)
    {
        var result = new ExpandoObject();
        IDictionary<string, object> dictionary = result;
        foreach (var property in source
            .GetType()
            .GetProperties()
            .Where(p => p.CanRead && p.GetMethod.IsPublic))
        {
            dictionary[property.Name] = property.GetValue(source, null);
        }
        return result;
    }
}

【讨论】:

    猜你喜欢
    • 2012-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-04
    • 1970-01-01
    • 1970-01-01
    • 2011-10-05
    • 2017-10-14
    相关资源
    最近更新 更多