这个班:
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) 我期望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)不返回任何元素?
注意:我永远不会依赖方法的实现细节,但我只是好奇.
我有一个(大)模板,想要替换多个值。替换需要不区分大小写。还必须能够拥有模板中不存在的键。
例如:
[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)