Func <t,u,=“”double =“”>等。作为构造函数中的参数</t,>

时间:2013-12-08 11:15:59

标签: c#

我从以下相对复杂的代码中提取了以下摘录

IDictionary<string, double> startingProbabilitiesDict = GetNewIDictionaryStringDouble();
IDictionary<string, double> transitionProbabilitiesDict = GetNewIDictionaryStringDouble();
IDictionary<string, double> emissionProbabilitiesDict = GetNewIDictionaryStringDouble();
...
var fbv = new SomeClass<string, string>
    (startingProbabilities: (s => startingProbabilitiesDict[s]), 
     transitionProbabilities: ((sOut, sIn) => transitionProbabilitiesDict[sOut][sIn]), 
     emissionProbabilities: ((s, o) => emissionProbabilitiesDict[s][o]));

SomeClass默认构造函数是

public class SomeClass<O, S> : IObserver<Tuple<O, IEnumerable<S>>>
{       
    ...
    public SomeClass(
        Func<S, double> startingProbabilities,
        Func<S, S, double> transitionProbabilities,
        Func<S, O, double> emissionProbabilities)
    {
        Contract.Requires(startingProbabilities != null);
        Contract.Requires(transitionProbabilities != null);
        Contract.Requires(emissionProbabilities != null);

        StartingProbabilities = startingProbabilities;
        TransitionProbabilities = transitionProbabilities;
        EmissionProbabilities = emissionProbabilities;
    }
    ...
}

我对这种表示法很困惑:

startingProbabilities: (s => startingProbabilitiesDict[s])

似乎startingProbabilities:指的是构造函数的fisrt参数,但是为什么冒号是必需的,这个符号叫什么?

1 个答案:

答案 0 :(得分:5)

它被称为Named parameter

该名称是可选的,如果您将使用与可选参数结合起来会更有趣(下面简化/简单示例):

[Test]
public void NamedAndUnnamedTest()
{
    Assert.AreEqual("Only value1 was supplied", DummyMethod(value1: 1));
    Assert.AreEqual("Only value1 was supplied", DummyMethod(1));
    Assert.AreEqual("Only value2 was supplied", DummyMethod(value2: 1));
    Assert.AreEqual("Both arguments were supplied", DummyMethod(1, 2));
}

private string DummyMethod(int value1 = 0, int value2 = 0)
{
    if (value1 != 0 && value2 != 0)
        return "Both arguments were supplied";
    if (value1 == 0)
        return "Only value2 was supplied";
    return "Only value1 was supplied";
}