Adding a Property to an existing class

前端 未结 2 1122
予麋鹿
予麋鹿 2021-01-19 07:05

I have a private class that I\'m using to implement certain properties. As such, I don\'t have the ability to modify the actual private class, and don\'t want to use inherit

2条回答
  •  渐次进展
    2021-01-19 07:41

    If you can access the data in the class that you need, and can live with methods instead of properties, look into extension methods, introduced in C# 3.0. From that article, here's an extension method added to the (sealed, non-modifiable) String class:

    public static class MyExtensions
    {
       public static int WordCount(this String str)
       {
           return str.Split(new char[] { ' ', '.', '?' }, 
                            StringSplitOptions.RemoveEmptyEntries).Length;
       }
    }   
    

    From the horse's mouth, extension properties are a possibility in a future version of C#.

    This won't help you if you need to access private fields or methods. In that case, you might look into reflection, but I'd advise staying away from that unless it's really necessary - it can get messy sometimes.

提交回复
热议问题