Dynamically adding properties to an Object from an existing static object in C#

僤鯓⒐⒋嵵緔 提交于 2019-12-14 03:54:43

问题


In my ASP .Net Web API Application while making the DB calls, some properties are needed to be added to the Model Class which already have some existing properties.

I understand I can use ExpandoObject in this case and add properties at run time, but I want to know how first to inherit all the properties from an existing object and then add a few.

Suppose for example, the object that's being passed to the method is ConstituentNameInput and is defined as

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; }
}

Now in my dynamically created object I want to add all these existing properties and then add a few named wherePartClause and selectPartClause.

How would I do that ?


回答1:


Well you could just create a new ExpandoObject and use reflection to populate it with the properties from the existing object:

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;
    }
}


来源:https://stackoverflow.com/questions/36686408/dynamically-adding-properties-to-an-object-from-an-existing-static-object-in-c-s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!