如何为 ToString 创建扩展方法?

发布于 2024-10-16 22:37:40 字数 421 浏览 6 评论 0原文

我已经尝试过:

public static class ListHelper
{
    public static string ToString<T>(this IList<String> list)
    {
        return string.Join(", ", list.ToArray());
    }

    public static string ToString<T>(this String[] array)
    {
        return string.Join(", ", array);
    }
}

但它对于 string[]List 都不起作用。也许我需要一些特殊的注释?

I have tried this:

public static class ListHelper
{
    public static string ToString<T>(this IList<String> list)
    {
        return string.Join(", ", list.ToArray());
    }

    public static string ToString<T>(this String[] array)
    {
        return string.Join(", ", array);
    }
}

But it does not work, both for string[] and List<string>. Maybe I need some special annotations?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

梦里人 2024-10-23 22:37:40

仅当没有匹配的适用候选方法时才检查扩展方法。在调用 ToString() 的情况下,总是有一个适用的候选方法,即 上的 ToString()对象。扩展方法的目的是扩展类型上可用的方法集,而不是覆盖现有方法;这就是为什么它们被称为“扩展方法”。如果您想重写现有方法,那么您必须创建一个重写方法。

Extension methods are only checked if there are no applicable candidate methods that match. In the case of a call to ToString() there will always be an applicable candidate method, namely, the ToString() on object. The purpose of extension methods is to extend the set of methods available on a type, not to override existing methods; that's why they're called "extension methods". If you want to override an existing method then you'll have to make an overriding method.

羅雙樹 2024-10-23 22:37:40

听起来您想替换 files.ToString() 返回的内容。如果不编写一个自定义类来将 files 指定为(即从 List 继承并覆盖 ToString()),您将无法做到这一点。

首先,摆脱泛型输入 (),您没有使用它。接下来,您需要重命名扩展方法,因为调用 files.ToString() 只会调用 List 的 ToString 方法。

这正是您正在寻找的。

static class Program
{
    static void Main()
    {
        var list = new List<string> { {"a"}, {"b"}, {"c"} };
        string str = list.ToStringExtended();
    }
}


public static class ListHelper
{
    public static string ToStringExtended(this IList<String> list)
    {
        return string.Join(", ", list.ToArray());
    }
}

It sounds like you want to replace what files.ToString() returns. You will not be able to do that without writing a custom class to assign files as (i.e. inherit from List and override ToString().)

First, get rid of the generic type (<T>), you're not using it. Next, you will need to rename the extension method because calling files.ToString()will just call the List's ToString method.

This does what you're looking for.

static class Program
{
    static void Main()
    {
        var list = new List<string> { {"a"}, {"b"}, {"c"} };
        string str = list.ToStringExtended();
    }
}


public static class ListHelper
{
    public static string ToStringExtended(this IList<String> list)
    {
        return string.Join(", ", list.ToArray());
    }
}
哽咽笑 2024-10-23 22:37:40

只是您不应该使用名称ToString作为扩展方法,因为它永远不会被调用,因为该方法已经存在并且您不应该使用 T 因为它在那里毫无用处。

例如,我尝试了这个,它再次返回相同的东西:

Console.WriteLine(lst.ToString<int>());

输出:

shekhar, shekhar, shekhar, shekhar

所以这次我使用了int,它仍然运行,因为除了更改方法原型之外,T 没有其他用途。

那么为什么您使用 ToString Literal 作为方法名称,因为它已经存在并且您无法在扩展方法中覆盖它,这就是您必须使用的原因T 使其通用。使用一些不同的名称,比如

public static string ToMyString(this IList<String> list)

这样,您就不必使用通用名称,因为它在那里毫无用处,您可以像往常一样简单地调用它。


这就是说你的代码对我有用。这是我尝试过的(在 LINQPAD 中):

void Main()
{

    List<string> lst = new List<string>();
    lst.Add("shekhar");
    lst.Add("shekhar");
    lst.Add("shekhar");
    lst.Add("shekhar");
    lst.ToString<string>().Dump();
}

    public static class ListHelper
    {
        public static string ToString<T>(this IList<String> list)
        {
            return string.Join(", ", list.ToArray());
        }

        public static string ToString<T>(this String[] array)
        {
            return string.Join(", ", array);
        }
    }

输出为 shekhar, shekhar, shekhar, shekhar

因为您已在 T 中指定了 T code>ToString在调用 ToString 方法时,您需要提及 stringint 等类型。

Simply you Shouldn't use the name ToString for the Extension method as it will never be called because that method already exist and you shouldn't use T as its useless there.

For example i tried this and again it returned same thing:

Console.WriteLine(lst.ToString<int>());

output:

shekhar, shekhar, shekhar, shekhar

so this time i used int and it still ran because that T has no use other then changing the Method Prototype.

So simply why are you using ToString Literal as Method name, as it already exist and you can't override it in a Extension method, this is the reason you had to use that T to make it generic. Use some different name like

public static string ToMyString(this IList<String> list)

That way you wouldn't have to use generic as it useless there and you could simply call it as always.


That said your code is working for me. here is what i tried (in LINQPAD):

void Main()
{

    List<string> lst = new List<string>();
    lst.Add("shekhar");
    lst.Add("shekhar");
    lst.Add("shekhar");
    lst.Add("shekhar");
    lst.ToString<string>().Dump();
}

    public static class ListHelper
    {
        public static string ToString<T>(this IList<String> list)
        {
            return string.Join(", ", list.ToArray());
        }

        public static string ToString<T>(this String[] array)
        {
            return string.Join(", ", array);
        }
    }

And the output was shekhar, shekhar, shekhar, shekhar

Since you have specified that T in ToString<T> you will need to mention a Type like string or int while calling the ToString method.

潜移默化 2024-10-23 22:37:40

您可以使用分部类覆盖特定类的 ToString。

例如,这是由实体框架脚手架生成的:

Namespace Models
    Public Class TPower
        Public Property Start As Date
        Public Property Finish As Date
        Public Property WattHours As Integer
    End Class
End Namespace

将其添加到单独的源文件中:

Namespace Models
    Partial Public Class TPower
        Public Overrides Function ToString() As String
            Return $"{Start}-{Finish} {WattHours}"
        End Function
    End Class
End Namespace

给出:

在此处输入图像描述

(将代码粘贴到 C# 的 Telerik 转换器 >;-)

You can override ToString for a specific class with a partial class.

For example, this was generated by Entity Framework scaffolding:

Namespace Models
    Public Class TPower
        Public Property Start As Date
        Public Property Finish As Date
        Public Property WattHours As Integer
    End Class
End Namespace

Adding this in a separate source file:

Namespace Models
    Partial Public Class TPower
        Public Overrides Function ToString() As String
            Return 
quot;{Start}-{Finish} {WattHours}"
        End Function
    End Class
End Namespace

Gives this:

enter image description here

(Paste code into the Telerik converter for C# >;-)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文