Add new property to string class C# [duplicate]

会有一股神秘感。 提交于 2019-12-01 03:14:56

问题


I am wondering if it is possible to add a new property as an extension property to the string class. What I'm looking for is something like this

string.Empty

I would like to make an extension, ex:

string.DisplayNone;

Can I add extension properties to the string C# class that I can call in a similar manner like when I do string.Empty?


回答1:


You can only build extensions for objects...

something like that:

class Program
{
    static void Main(string[] args)
    {
        string x = "Hello World";
        x.DisplayNow();
    }
}

public static class StringExtension
{
    public static void DisplayNow(this string source)
    {
        Console.WriteLine(source);
    }
}

but i've never seen how u can extend a struct or a class which has never been initialized.




回答2:


Yeah, you can do this.. however it will be an extension method, not a property.

public static class Extensions
{
    public static string DisplayNone(this string instance)
    {
        return "blah";
    }
}

Which would need to be used (however hacky) as "".DisplayNone(); as it will require an instance of a string to be created.

If you wanted to though, another slightly less hacky way would be to create a helper class..

public static StringHelper
{
    public static string DisplayNone()
    {
        return "blah";
    }
}



回答3:


You might be able to create your own value type. That mimics the type String with a "DisplayName" method.

However, I can't see why you need "DisplayName" on the type? It makes more sense on the sting instance. I.e. "Hello".DisplayName. See Smokefoot's answer to this question.



来源:https://stackoverflow.com/questions/6783239/add-new-property-to-string-class-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!