怎么写扩展方法?

mathieuxiao 2013-12-10 12:39:48
现在有classA,classB两个类,我想为classA和classB写一个扩展方法,但是不希望其他类能够具有这个扩展方法,这里应该如何对泛型参数T进行限制?
public static T SomeMethod<T>(this T source, object param)
{
....
}
...全文
190 12 打赏 收藏 转发到动态 举报
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
mathieuxiao 2013-12-10
  • 打赏
  • 举报
回复
classA,classB之间没有任何关系,也不可以进行修改
bigbaldy 2013-12-10
  • 打赏
  • 举报
回复
让classA和classB继承于同一个借口,然后扩展方法where T:那个接口
sj490790083 2013-12-10
  • 打赏
  • 举报
回复
引用 7 楼 sj490790083 的回复:
封装一个classA和classB的父类RootClass, 然后写RootClass的扩展方法 public static void Function<T>(this T aa)where T:RootClass { XXXXX; }
那就定义2个方法分别扩展A和B
宝_爸 2013-12-10
  • 打赏
  • 举报
回复
引用 9 楼 mathieuxiao 的回复:
[quote=引用 3 楼 findcaiyzh 的回复:] 这个好像只能写两遍了吧。要不用Object作为参数,函数内用反射?
我是希望只能在这两个类的实例上才显示扩展方法,其他类型实例就不会显示[/quote] 那就写两遍吧, 或者封装一个函数,参数是Object,用反射调用。扩展函数中调用这个封装的函数。
mathieuxiao 2013-12-10
  • 打赏
  • 举报
回复
引用 3 楼 findcaiyzh 的回复:
这个好像只能写两遍了吧。要不用Object作为参数,函数内用反射?
我是希望只能在这两个类的实例上才显示扩展方法,其他类型实例就不会显示
mathieuxiao 2013-12-10
  • 打赏
  • 举报
回复
引用 7 楼 sj490790083 的回复:
封装一个classA和classB的父类RootClass, 然后写RootClass的扩展方法 public static void Function<T>(this T aa)where T:RootClass { XXXXX; }
classA和classB都已经封装好了,不能改代码
sj490790083 2013-12-10
  • 打赏
  • 举报
回复
封装一个classA和classB的父类RootClass, 然后写RootClass的扩展方法 public static void Function<T>(this T aa)where T:RootClass { XXXXX; }
cy_nobuda 2013-12-10
  • 打赏
  • 举报
回复
public static T SomeMethod<T>(this T source, object param) where T : class, ICloneable { .... } 通过后面的where来限制
cy_nobuda 2013-12-10
  • 打赏
  • 举报
回复
扩展方法被定义为静态方法,但它们是通过实例方法语法进行调用的。 它们的第一个参数指定该方法作用于哪个类型,并且该参数以 this 修饰符为前缀。 扩展方法的要求如下: 1 第一个参数是要扩展或者要操作的类型,这称为"被扩展的类型" 2 为了指定扩展方法,要在被扩展的类型名称前面附加this修饰符 3 要将方法作为一个扩展方法来访问,要用using指令导入扩展类型的命名空间,或者使扩展类型和调用代码在同一个命名空间中. //扩展方法必须在非泛型静态类中定义 public static class qzwtest { //扩展方法 public static string[] qzw(this string str) { return str.Split(new char[] { ' ', ',' }); } } class Program { static int Main() { string testStr = "钱卓文 is 喵喵,贤静"; //调用扩展方法 string[] testArray = testStr.qzw(); foreach (string s in testArray) { Console.WriteLine(s); } Console.ReadKey(); return 0; } }
  • 打赏
  • 举报
回复
扩展方法只能扩展到一种类型上,即第一个参数,且必须用this指明 public static T Test<T, R>(this T t, R r) where T : A where R : B 要么另外再封装一个泛型类,再写扩展 public class C<T, R> where T : A where R : B {} public static C Test(this C c, object param) public static T Test<T>(this T t, object param) where T : C
宝_爸 2013-12-10
  • 打赏
  • 举报
回复
这个好像只能写两遍了吧。要不用Object作为参数,函数内用反射?
mathieuxiao 2013-12-10
  • 打赏
  • 举报
回复
自己顶一个,帮顶就有分啊

110,538

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧