添加一个属性到现有的类 [英] Adding a Property to an existing class

查看:91
本文介绍了添加一个属性到现有的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我使用来实现某些属性的私有类。因此,我没有修改实际的私有类的功能,并且不想使用继承代替它来创建自己的类。有没有一种方法,我可以将属性到私有类添加?

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 inheritance to create my own class in place of it. Is there a way where I can add properties to that private class?

谢谢!

推荐答案

如果您可以访问你需要的类中的数据,并能与方法,而不是性质居住,考虑的扩展方法中,介绍了C#3.0。从这篇文章中,这里的加入(密封的,不可修改)String类的扩展方法:

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;
   }
}   



从的马的嘴,扩展的属性的在C#的未来版本的可能性。

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.

这篇关于添加一个属性到现有的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆