动态添加属性到对象 [英] Dynamically adding properties to object

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

问题描述

嗨朋友们,

我有型号说

Hi friends,
I have model say

 public class GenericPaymentMethod<T>
    {
        public int TenantID { get; set; }
        public string Market { get; set; }
        public List<T> CreditCard { get; set; }
        public List<T> DebitCard { get; set; }
        public List<T> BPay { get; set; }
    }
public class EditPaymentMethod
    {
        public GenericPaymentMethod<Multicheckbox> MyProperty { get; set; }
    }
public class Multicheckbox
    {
        public string CheckboxName { get; set; }
        public bool IsChecked { get; set; }
    }



我正在创建如下模拟数据


I'm creating mock data as follows

public static EditPaymentMethod GetPaymentMethodDetails(int tenantID) {
            dynamic obj = new EditPaymentMethod();
            obj.MyProperty = new GenericPaymentMethod<Multicheckbox>();

            obj.MyProperty.TenantID = 1000;

            obj.MyProperty.Market = "AU";

            obj.MyProperty.CreditCard = new List<Multicheckbox>(){
                new Multicheckbox { CheckboxName = "Amex", IsChecked = true },
                new Multicheckbox { CheckboxName = "Master Card", IsChecked = false },
                new Multicheckbox { CheckboxName = "Visa", IsChecked = true }
            };

            obj.MyProperty.DebitCard = new List<Multicheckbox>(){
                new Multicheckbox { CheckboxName = "Amex", IsChecked = false },
                new Multicheckbox { CheckboxName = "Master Card", IsChecked = true },
                new Multicheckbox { CheckboxName = "Visa", IsChecked = false }
            };

            obj.MyProperty.BPay = new List<Multicheckbox>(){
                new Multicheckbox { CheckboxName = "Savings Cheque", IsChecked = true },
                new Multicheckbox { CheckboxName = "Credit Card", IsChecked = false },
            };

            for (int i = 0; i < obj.MyProperty.BPay.Count; i++)

            {

                obj.BillerCodes = new List<string> { "AAA", "BBB" };
            }

            return obj;
        }



我想根据BPay中的项目号动态地向对象添加属性。



知道如何去做吗?



提前谢谢


I want to dynamically add properties to the object based on the no of item present in the BPay.

Any idea how to go about it?

Thanks in advance

推荐答案

Dynamic允许对强类型对象进行松散类型访问。



您应该使用ExpandoObject类,它允许对内部字典进行松散类型访问:



dynamic configObject = new ExpandoObject();



configObject.Git = new GitCheckout {

Repository = config.Github.Url

};
Dynamic allows loosely-typed access to strongly-typed objects.

You should use the ExpandoObject class, which allows loosely-typed access to an internal dictionary:

dynamic configObject = new ExpandoObject();

configObject.Git = new GitCheckout {
Repository = config.Github.Url
};


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

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