从C#中的现有静态对象动态添加属性到Object

Str*_*der 2 c# dynamic expandoobject

在我的ASP的.NET Web API应用,同时使DB调用,需要一些属性被添加到模型类已经有一些现有的属性.

我明白我可以使用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; }
}
Run Code Online (Sandbox Code Playgroud)

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

我该怎么办?

Jon*_*eet 13

那么你可以创建一个新的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;
    }
}
Run Code Online (Sandbox Code Playgroud)