从C#中的现有静态对象向对象动态添加属性 [英] Dynamically adding properties to an Object from an existing static object in C#

查看:1594
本文介绍了从C#中的现有静态对象向对象动态添加属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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.

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

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

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

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

我该怎么做?

推荐答案

好吧,您只需创建一个新的ExpandoObject并使用反射将现有对象的属性填充到其中:

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

这篇关于从C#中的现有静态对象向对象动态添加属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆