Click here to Skip to main content
15,850,360 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I want to extend a custom class attributes
I do not know how to achieve it.

example:
C#
public class TestClass
{
   public ID { get; set }
   public Name { get; set }
}


I need to add multiple attributes,Such as "Address,Phone"...
How can I do it?
Posted

1 solution

Strictly speaking, you cannot do it. However, with reflection you can create types dynamically, but for this purpose you have to create a whole assembly on the fly. Such approach is rarely used and very fruitful for certain areas, but hardly for your goals (which you did not bother to share with us, so I cannot be 100% sure). If you create some type members on the fly, the part of code which is supposed to use these dynamically defined properties "does not know" them at compile time, so how can you use those properties? For many applications, it doesn't matter, because dynamically created assembly can, for example, implement statically defined interfaces.

Most likely, if you analyze your ultimate goals thoroughly, you will see that you don't really need this feature. Instead, you can model such "dynamic property" using normal statically defined type (structure or class). Here is how: for some property type, create a dictionary indexed with string used as dictionary keys, each such string representing "property name".

It's easier to demonstrate on some reference type. Say, you have some class called MyPropertyType. Create a "set of dynamic properties" using the type System.Collections.Generic.Dictionary<string, MyPropertyType>. When the instance of the declaring type is created, you can populate this dictionary dynamically, using string keys (look at these string as at the "property names") and instances of MyPropertyTypes. Then, with this dictionary, you can access the instance of MyPropertyType and read and modify these instances by those string keys. Please see: http://msdn.microsoft.com/en-us/library/xfhwa508%28v=vs.110%29.aspx[^].

Most likely, you will want to implement this mechanism for several "property types". Then you can create some universal generic class based on generic dictionary and abstracting out only the "property type" (the "property name" type may remain string for all cases, but this is not a must; you can identify these modeled "properties" with any other suitable type, depending on our requirements).

—SA
 
Share this answer
 
Comments
fengyuchun88 5-Jan-15 23:55pm    
thank you ^_^
Sergey Alexandrovich Kryukov 6-Jan-15 10:37am    
You are very welcome.
Good luck, call again.
—SA
Manoj Kumar Choubey 6-Jan-15 0:27am    
Nice answer sir +5
Sergey Alexandrovich Kryukov 6-Jan-15 10:37am    
Thank you, Manoj.
—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900