2

是否可以在 C# 中(我认为不是)扩展int以实现接口(不创建包装类)?

我有一个这样的界面

public interface IActionLoggerObject
{
    string GetForLogging();
}

我希望(从概念上)能够做到这一点:

public class int:IActionLoggerObject
{
    string IActionLoggerObject.GetForLogging() { return "s"; }
}
4

3 回答 3

8

是否有可能(我认为不可能)(在 c# 中)扩展“int”来实现接口(不创建包装类)?

不,您永远无法更改现有类型实现的接口。

目前尚不清楚您为什么要这样做,但几乎可以肯定的是,创建一个包装类是前进的方向。

于 2012-06-19T20:27:17.737 回答
3

正如 MNGwinn 在他对 Jon Skeet 回答的评论中提到的那样,如果它们满足您的所有要求,您可以使用扩展方法。

所以,像这样:

public static class ExtensionMethods
{
    public static string GetForLogging(this int @this)
    {
        return "s"; // or maybe return @this.ToString();
    }
}

会让你这样做。

string val = 3.GetForLogging();
于 2012-06-19T20:51:41.743 回答
0

另一种扩展方法的可能性:

public interface IActionLoggerObject
{
    string GetForLogging();
}

public class ActionLoggerObjectInt : IActionLoggerObject
{
    public string GetForLogging()
    {
        return "s";
    }
}

public static class ExtensionMethods
{
    public static IActionLoggerObject AsActionLoggerObject(this int i)
    {
        return new ActionLoggerObjectInt();
    }
}

用法:

Console.WriteLine(32.AsActionLoggerObject().GetForLogging());
LoggingMethod(32.AsActionLoggerObject());
于 2016-05-02T21:30:07.133 回答