小编Ale*_*man的帖子

C#6.0中的类可以有受保护的主构造函数吗?

这个班:

class Person 
{
    public Person(string firstName, string lastName)
    {
        _firstName = FirstName;
        _lastName = lastName;
    }

    private readonly string _firstName; // Make it really immutable
    public string FirstName
    {
        get
        {
            return _firstName;
        }
    }

    private readonly string _lastName; // Make it really immutable
    public string LastName
    {
        get
        {
            return _lastName;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

可以使用构造函数在C#6.0版中重写为:

class Person(string firstName, string lastName)
{
    public string FirstName { get; } = firstName;
    public string LastName { get; …
Run Code Online (Sandbox Code Playgroud)

c# c#-6.0

21
推荐指数
3
解决办法
2257
查看次数

为什么Enumerable.Empty()返回一个空数组?

我期望Enumerable.Empty()的实现就是这样:

public static IEnumerable<TResult> Empty<TResult>()
{
    yield break;
}
Run Code Online (Sandbox Code Playgroud)

但实现是这样的:

public static IEnumerable<TResult> Empty<TResult>()
{
    return EmptyEnumerable<TResult>.Instance;
}

internal class EmptyEnumerable<TElement>
{
    private static volatile TElement[] instance;

    public static IEnumerable<TElement> Instance
    {
        get
        {
            if (EmptyEnumerable<TElement>.instance == null)
                EmptyEnumerable<TElement>.instance = new TElement[0];
            return (IEnumerable<TElement>)EmptyEnumerable<TElement>.instance;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

为什么实现比一行代码更复杂?返回缓存数组是否有优势而不是(yield)不返回任何元素?

注意:我永远不会依赖方法的实现细节,但我只是好奇.

c# linq linq-to-objects

10
推荐指数
1
解决办法
838
查看次数

如何使用 StringBuilder 进行多个不区分大小写的替换

我有一个(大)模板,想要替换多个值。替换需要不区分大小写。还必须能够拥有模板中不存在的键。

例如:

[TestMethod]
public void ReplaceMultipleWithIgnoreCaseText()
{
    const string template = "My name is @Name@ and I like to read about @SUBJECT@ on @website@, tag  @subject@";  
    const string expected = "My name is Alex and I like to read about C# on stackoverflow.com, tag C#";
    var replaceParameters = new List<KeyValuePair<string, string>>
    {
        new KeyValuePair<string, string>("@name@","Alex"),
        new KeyValuePair<string, string>("@subject@","C#"),
        new KeyValuePair<string, string>("@website@","stackoverflow.com"),
        // Note: The next key does not exist in template 
        new KeyValuePair<string, string>("@country@","The Netherlands"), 
    };
    var actual = ReplaceMultiple(template, …
Run Code Online (Sandbox Code Playgroud)

c# stringbuilder

3
推荐指数
1
解决办法
3342
查看次数

标签 统计

c# ×3

c#-6.0 ×1

linq ×1

linq-to-objects ×1

stringbuilder ×1