C#在运行时添加的属性 [英] C# add properties at runtime

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

问题描述

我读过几篇文章,而我仍然有在运行系统中添加属性一类的麻烦。它应该是简单的,因为我有这样一个类:

I've read few posts, and I'm still having troubles with adding properties to a class in runtime. It should be simple, because I have a class like this:

public class MyClass
    {
        String Template;
        String Term;
     }



在运行时,我要补充几个属性,如电话,电子邮件(它依靠...)。
可能有人请解释一下我如何类初始化过程中添加这些属性?

During runtime, I have to add few attributes, like Phone, Email (it depends...). Could someone please explain me how to add these properties during class initialization?

Srecko

推荐答案

我不认为增加一个属性是在这里做正确的事情。
类似电子邮件或手机的属性是一个键和一个值的只是一些额外的对。你可以使用词典,但这样会阻止你使用一键不止一次(多个电子邮件地址,例如接触)。所以,你也可以同样使用一个列表与LT; KeyValuePair<字符串,字符串>> 。这样的:

I don't think adding a property is the right thing to do here. The attributes like "Email" or "Phone" are just some additional pairs of a key and a value. You could use a Dictionary, but that would prevent you from using a key more than once (more than one email address for a contact for example). So you could just as well use a List<KeyValuePair<string, string>>. Like that:

public class MyClass
{
    String Template;
    String Term;
    public List<KeyValuePair<string, string>> Attributes { get; private set; }

    public MyClass() {
        Attributes = new List<KeyValuePair<string, string>();
    }

    public void AddAttribute(string key, string value) {
        Attributes.Add(new KeyValuePair<string, string>(key, value));
    }
}

// to be used like this: 
MyClass instance = new MyClass();
instance.AddAttribute("Email", "test@example.com");
instance.AddAttribute("Phone", "555-1234");

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

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