开发者

How can I extend a model from a different assembly?

How can I add a property to a model that was created in an other assembly. We have many applications ranging from desktop applications to web applications so I have class library with each model needed along with their relationships. I am very easily able to reference my class library and query what is needed. However, due to the fact that I am not modelling every field in each table (some tables have upwards of 30+ fields).

How can 开发者_运维知识库I extend the original model to give it more properties? Or should I simply model everything in the tables that I am using? My original thinking was that it would be nice if the developer could extend any model to his will to fit his project needs.


you may inherit your own class of a new assembly form base class of old assembly if you have a reference to the old one and that class is public.


In addition to what Arseny is suggesting, you may "fake extending the class" by adding so-called extension methods. As an example you could extend string like this:

public static class StringExtensions 
{
    public static string Affix(this string source, string prefix, string suffix)
    {
        return string.Format("{0}{1}{2}", prefix, source, suffix);
    }
}

Which only utilizes publicly exposed stuff on the class it's extending and so it doesn't break the contract of not modifying somebody elses class without owning the source code. But it adds syntactic sugar letting you call the class as if you had indeed modified it, like this:

string myString = "MyString";
string result = myString.Affix("Before", "After");
// result contains "BeforeMyStringAfter"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜