【问题标题】:Can I use inheritance with an extension method?我可以将继承与扩展方法一起使用吗?
【发布时间】:2012-10-24 15:28:57
【问题描述】:

我有以下几点:

public static class CityStatusExt
{
    public static string D2(this CityStatus key)
    {
        return ((int) key).ToString("D2");
    }


public static class CityTypeExt
{
    public static string D2(this CityType key)
    {
        return ((int) key).ToString("D2");
    }

加上其他具有类似扩展名的类,它们返回格式为“D2”的键

有没有办法我可以从基类继承并让基类提供功能所以 难道我不用重复同样的扩展方法代码吗?

更新。很抱歉我没有提到这一点,但我的类如 CityType 是 Enums。

【问题讨论】:

  • 是的,你可以。您唯一失去的就是拥有自定义实现的能力..

标签: c#


【解决方案1】:

您可以将方法设为通用。 C# 将推断类型:

public static class Extension 
{ 
    public static string D2<T> (this T key) 
    { 
        return ((int)(object) key).ToString("D2"); 
    } 
}

【讨论】:

  • 这不会按原样编译。您不能将 T 转换为 int
  • 我已经编辑过了。不过,如果您知道 T 是什么,那么 where 子句会更有意义。
  • 类型是枚举类型,但是,where 子句没有帮助。此外,(int)(object)key 强制转换仅在枚举具有默认基础类型 int 时才有效。
【解决方案2】:

从下面的评论中,CityTypeCityStatus 是枚举。因此,您可以这样做:

public static class Extensions
{
    public static string D2(this Enum key)
    {
        return Convert.ToInt32(key).ToString("D2");
    }
}

原答案:

可以使用泛型方法和接口ID2Able

public static class Extensions
{ 
    public static string D2<T>(this T key) where T : ID2Able
    { 
        return ((int) key).ToString("D2"); 
    } 
}

这样扩展方法不会出现在所有类型中;它仅适用于您从 ID2Able 继承的东西。

【讨论】:

  • 如果枚举的基础类型是 uint、long 或 ulong,Convert.ToInt32 可能会丢失信息。
【解决方案3】:

您的枚举已经都继承自一个公共基类,即System.Enum。所以你可以这样做(枚举不接受“D2”作为格式字符串,但它们接受“D”,所以我添加了对 PadLeft 的调用):

public static class EnumExtensions
{
    public static string D2(this Enum e)
    {
        return e.ToString("D").PadLeft(2, '0');
    }
}

【讨论】:

  • 这很好也很简单,但比Convert.ToInt32(key).ToString("D2")ToInt64 慢 :) 当然,这只有在速度真的是本质:)
  • @flindeberg 你介绍过它吗?你怎么知道它变慢了?
  • 我做了@phoog,e.ToString("D") 运行时间为Convert.ToInt64(e).ToString("D2") 的 90%,但加上PadLeft,它变得慢了大约 50%,即Convert.ToInt64(e).ToString("D2") 时间因子 1, e.ToString("D").PadLeft(2,'0'),时间因子为 1.33。除非速度真的至关重要,并且您正在进行大量转换,否则这真的没什么大不了的:)
  • @flindeberg 时间差异取决于整数值是 1 个字符还是更多——如果它的长度 >= 长度参数,pad 将返回相同的字符串。但是,我仍然对 1000 万次迭代进行了一些计时,发现每次迭代使用较慢的代码大约需要 0.41 微秒,而使用较快的代码则需要 0.36 微秒。所以“很多”可能是轻描淡写;-)
  • @flindeberg 尝试 JohnB 编辑的答案中建议的 (int)(object)key 演员表。它确实快得多(但只有在您知道所有枚举都将 int 作为其基础类型时才有效)。
猜你喜欢
  • 2010-11-11
  • 2023-03-08
  • 1970-01-01
  • 2014-02-15
  • 1970-01-01
  • 2018-03-14
  • 2012-09-03
  • 2017-03-16
  • 1970-01-01
相关资源
最近更新 更多