开发者

OOP principles in C#

开发者 https://www.devze.com 2023-04-05 05:47 出处:网络
I have a library (no source), to an certain object of which, I need 开发者_JAVA百科to add some properties.

I have a library (no source), to an certain object of which, I need 开发者_JAVA百科to add some properties. What would be the a way to do it ? I'm aware I could extend the class and add properties to the child. As well I know there are NO Extension Properties in C# yet. What would you suggest ? Thank you !

The metadata of class could be something like :

 public class ResultClass
 {
    public IList<Item> Results { get; set; }
    public int TotalResults { get; set; }
 }

and I want to add a :

 String description;

to it. Thanks.


There are a couple strategies you could take. Inheritance is the most obvious one. You might also consider composition. Can you give us some more details about what the object is and what properties you need to add to it and why?

After seeing the expanded question:

Either strategy outlined above (composition or inheritance) will probably work for you. Personally, I prefer composition. I think it better insulates you from changes that might be made to the third party library. It also forces you to work through the public interface of the library class, which is preferable when you have no knowledge or control of the internals of a class.

Here is the most basic example of composition.

public CompositeClass
{
    private ResultClass _resultClass = new ResultClass();

    public IList<Item> Results
    {
        get { return _resultClass.Results; }
        set { _resultClass.Results = value; }
    }

    public int TotalResults
    {
        get { return _resultClass.TotalResults; }
        set { _resultClass.TotalResults = value; }
    }

    //
    // New Property
    //
    public string Description { get; set; }
}


Why do you need to add properties? If this is for binding purposes then I would suggest creating a wrapper class or creating your own inherited type that can raise PropertyChanged events in response to various state changes in your third party types. Instead of telling us your proposed solution you should tell us the actual problem you are trying to solve. Also (as I can't vote to close/migrate), this is not really a valid discussion for this site.


I think you are mixing up Extension Methods with Extension Properties. And the last ones do not exist in C#. So you should extend the class or create an inheriting class.

0

精彩评论

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