Dynamically adding properties to an Object from an

2019-07-08 08:35发布

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条回答
劫难
2楼-- · 2019-07-08 09:22

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;
    }
}
查看更多
登录 后发表回答