且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C#在运行时添加的属性

更新时间:2023-12-06 15:35:52

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