使用静态函数扩展字符串类

时间:2016-05-02 18:22:41

标签: c# string extension-methods

我试图扩展' String'类。 到目前为止,我必须在声明的字符串对象上创建扩展函数。

String s = new String();
s = s.Encrypt();

但是我想为类本身创建一个扩展函数。 在这种情况下,例如:String s = String.GetConfig("Test");

到目前为止我尝试了什么:

using System;
using System.Runtime.CompilerServices;

namespace Extensions.String
{
    public static class StringExtensions
    {
       // Error
        public string DecryptConfiguration
        {
            get
            {
                return "5";
            }
        }

        // Can't find this
        public static string GetConfig(string configKey);
        // Works, but not what I would like to accomplish
        public static string Encrypt(this string thisString);
    }
}

非常感谢任何帮助。 提前谢谢!

1 个答案:

答案 0 :(得分:0)

您无法在类上添加像静态方法一样调用的扩展方法(例如var s = String.ExtensionFoo("bar"))。

扩展方法需要一个对象的实例(例如在StringExtensions.Encrypt示例中)。从根本上说,扩展方法是静态方法;他们的诀窍是使用this关键字来启用类似实例的调用(更多细节here)。

你最好的选择是某种包装:

using System;
using System.Runtime.CompilerServices;

namespace Extensions.String
{
    public static class ConfigWrapper//or some other more appropriate name
    {
        public static string DecryptConfiguration
        {
            get
            {
                return "5";
            }
        }


        public static string GetConfig(string configKey);

        public static string Encrypt(string str);
    }
}

可以像这样调用:

var str1 = ConfigWrapper.DecryptConfiguration;
var str2 = ConfigWrapper.GetConfig("foo");
var str3 = ConfigWrapper.Encrypt("bar");
相关问题