【问题标题】:Extend string class with static functions用静态函数扩展字符串类
【发布时间】:2016-08-27 14:37:45
【问题描述】:

我正在尝试扩展“字符串”类。 到目前为止,我已经在声明的字符串对象上创建了扩展函数。

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);
    }
}

任何帮助将不胜感激。 提前谢谢!

【问题讨论】:

标签: c# string extension-methods


【解决方案1】:

你不能像类的静态方法一样添加你调用的扩展方法(例如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");

【讨论】:

    猜你喜欢
    • 2013-07-24
    • 2015-07-05
    • 1970-01-01
    • 1970-01-01
    • 2015-05-17
    • 2018-07-03
    • 2010-11-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多