简体   繁体   English

在没有委托的情况下将方法用作C#中的参数?

[英]Using methods as parameters in C# without delegates?

I was going over some code that a knowledgeable colleague wrote and I came across a technique I found confusing. 我正在查看一些知识渊博的同事编写的代码,并且遇到了一种令我感到困惑的技术。 Here is a snippet of code ... 这是一段代码...

public class TaxController : ApiController
{
    private StateTaxApi taxApi = new taxApi();

    [HttpGet]
    public async Task<IEnumerable<String>> GetStatesOwedTax(String taxId, String clientId)
    {
        try
        {
            return await taxApi.GetStatesOwedTax(clientId, GetTaxId(), GetClientId());
        }
        catch (Exception e)
        {
            throw new ApiException(HttpStatusCode.BadRequest, "Could not get tax states", e);
        }           
    }

    private String GetClientId()
    {
        try
        {
            return Request.Headers.GetValues("client-id").FirstOrDefault();
        }
        catch (InvalidOperationException e)
        {
            // TODO: Handle error here
        }

        return null;
    }

    private String GetTaxId()
    {
        return GetSessionValue("taxId") as String;
    }

    private Object GetSessionValue(String key)
    {
        var context = Request.Properties["MS_HttpContext"] as HttpContextWrapper;
        var session = context.Session;
        return session[key];
    }
}

Here you can see the methods are being passed as parameters to the method GetStatesOwedTax() : 在这里,您可以看到方法作为参数传递给方法GetStatesOwedTax()

return await taxApi.GetStatesOwedTax(clientId, GetTaxId(), GetClientId());

I thought the only way to do this was to use a delegate to represent the method being passed in as a parameter. 我认为唯一的方法就是使用委托来表示要作为参数传递的方法。 I see no mention of Func(string) defining the delegates. 我没有提到定义代表的Func(string) What am I missing? 我想念什么?

The method isn't being passed, the result of the method is being passed. 该方法未通过,该方法的结果正在通过。 As simple as that is to say, I find an example always serves better. 这么简单,我发现一个例子总是更好。

public void Start()
{
    var result = DoMath(GetX(), GetY());
}

public int GetX()
{
    return 1;
}

public int GetY()
{
    return 2;
}

public int DoMath(int x, int y)
{
    return x + y;
}

As you can see in the example, DoMath() needs two ints passed into it. 在示例中可以看到, DoMath()需要将两个int传递给它。 In lieu of 替代

public void Start()
{
    var x = GetX();
    var y = GetY();
    var result = DoMath(x, y);
}

you can do the method calls directly in the parameters of the DoMath() method. 您可以直接在DoMath()方法的参数中进行方法调用。

Now, whether this is simpler, better, good/bad practice all comes down to personal style and overall complexity. 现在,这是否更简单,更好,更好/不好的做法都取决于个人风格和整体复杂性。 If it's very readable then you can save space by doing this, but it does risk muddying up the waters and not being as apparent to what you're doing. 如果它可读性强,那么您可以通过这样做节省空间,但是这样做确实有使泥泞的水面变得模糊不清的风险。 So I can't say if you should or should not do it, just saying that you can do it. 因此,我不能说您是否应该这样做,只是说您可以做到。

As mentioned by Vilx in the comments, an easy way to tell if the method is being passed vs the results of the method are the inclusion of the parenthesis. 正如Vilx在评论中所提到的那样,一种简单的方法来判断该方法是否通过,而方法的结果则是包含括号。 If they are there (as they are in this case) then it means the method will be evaluated and its result used. 如果它们在那里(如本例所示),则意味着将对该方法进行评估并使用其结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM