相关疑难解决方法(0)

我可以将扩展方法添加到现有的静态类中吗?

我是C#中扩展方法的粉丝,但是没有成功将扩展方法添加到静态类,例如Console.

例如,如果我想向Console添加一个名为'WriteBlueLine'的扩展,那么我可以去:

Console.WriteBlueLine("This text is blue");
Run Code Online (Sandbox Code Playgroud)

我尝试通过添加一个本地的公共静态方法,将Console作为'this'参数...但没有骰子!

public static class Helpers {
    public static void WriteBlueLine(this Console c, string text)
    {
        Console.ForegroundColor = ConsoleColor.Blue;
        Console.WriteLine(text);
        Console.ResetColor();
    }
}
Run Code Online (Sandbox Code Playgroud)

这没有向Console添加'WriteBlueLine'方法......我做错了吗?或者要求不可能?

c# extension-methods static

519
推荐指数
11
解决办法
18万
查看次数

将扩展方法添加到字符串类 - C#

不知道我在这里做错了什么.无法识别扩展方法.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using StringExtensions;


namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            RunTests();
        }

        static void RunTests()
        {
            try
            {
                ///SafeFormat
                SafeFormat("Hi There");

                SafeFormat("test {0}", "value");

                SafeFormat("test missing second value {0} - {1}", "test1");

                SafeFormat("{0}");

                //regular format
                RegularFormat("Hi There");

                RegularFormat("test {0}", "value");

                RegularFormat("test missing second value {0} - {1}", "test1");

                RegularFormat("{0}");

                ///Fails to recognize the extension method here
                string.SafeFormat("Hello");

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            Console.ReadLine();
        } …
Run Code Online (Sandbox Code Playgroud)

.net c# string extension-methods string-formatting

14
推荐指数
2
解决办法
2万
查看次数

如何在c#中扩展字符串类来改变它的行为?

我不喜欢字符串的行为方式,还有一些我想改变的其他事情.

看起来字符串无法扩展,因为它是一个密封的类.

还有另外一种方法吗?我可以复制源代码并创建我自己的类但是它与字符串不兼容,或者我可以使它兼容吗?

c# string

2
推荐指数
1
解决办法
85
查看次数

标签 统计

c# ×3

extension-methods ×2

string ×2

.net ×1

static ×1

string-formatting ×1