c# – 可以在.net中扩展String类

前端之家收集整理的这篇文章主要介绍了c# – 可以在.net中扩展String类前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何覆盖或扩展.net主类.例如 @H_404_2@public class String { public boolean contains(string str,boolean IgnoreCase){...} public string replace(string str,string str2,boolean IgnoreCase){...} }

@H_404_2@string aa="this is a Sample"; if(aa.contains("sample",false)) {...}

可能吗?

解决方法

String类是密封的,因此您无法从中继承.扩展方法是您最好的选择.它们与实例方法具有相同的感觉,而没有继承成本. @H_404_2@public static class Extensions { public static bool contains(this string source,bool ignoreCase) {... } } void Example { string str = "aoeeuAOEU"; if ( str.contains("a",true) ) { ... } }

您需要使用VS 2008才能使用扩展方法.

猜你在找的C#相关文章