【问题标题】:Why can I add extensions methods to the string class but not to DateTime? [closed]为什么我可以将扩展方法添加到字符串类而不是 DateTime? [关闭]
【发布时间】:2021-09-19 13:40:17
【问题描述】:

如果我做这样的方法:

public static void ExtMethod(this string);

如果我这样调用它就会显示出来:

string str = "";
str.ExtMethod();

但如果我这样做:

public static void ExtMethod(this DateTime);

这不起作用:

DateTime date;
date.ExtMethod();

我必须这样称呼它:

ExtMethod(date);

那为什么我可以为字符串做一个扩展方法,而不能为 DateTime 做一个扩展方法呢?

【问题讨论】:

  • 错误信息是什么? “不起作用”是什么意思?
  • 它应该可以工作。您是否缺少扩展类命名空间的 using 指令?
  • 您当前的扩展方法都不会编译,因为您没有为参数提供名称。请注意,假设您看到的错误消息实际上是关于明确分配的(根据 kordiseps 的回答),如果您没有为变量分配初始值,那么您的字符串扩展方法会看到相同的内容。
  • @mummy 请分享minimal reproducible example
  • @Steeeve:没有显示完整示例(甚至没有显示错误消息)的问题在于,不清楚哪些问题只是拼写错误,哪些问题实际上在 OP 的代码中。

标签: c# extension-methods


【解决方案1】:

日期变量未赋值。您需要分配一些值。
例如

DateTime date = DateTime.Now;//or some value else
date.ExtMethod();

而不是

DateTime date;
date.ExtMethod();

【讨论】:

  • 天啊!是的,那是我的问题。我凭直觉想像DateTime.ExtMethod() 一样使用它,但这不是扩展方法,谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-12-13
  • 1970-01-01
  • 1970-01-01
  • 2010-09-19
  • 1970-01-01
相关资源
最近更新 更多