C#中相同类型的多个别名

我更喜欢将Delegates作为参数。 所以我通常会遇到一个委托的多个参数属于同一类型的情况,我试图使其更具可读性。为此,请尝试使用c#关键字“ using”指令。

using System;
using FirstNumber = System.Int32;
using SecondNumber = System.Int32;
using Result = System.Int32;

public class FunctionPointers
{
    Func<FirstNumber, SecondNumber, Result> add;

    public FunctionPointers(Func<FirstNumber, SecondNumber, Result> op)
    {
        add = op;
    }
}

Intellisense snapshot From the screen shot, it is clear that alias name is same for all arguments. Is there a way to correct this? or usage of aliases is incorrect?

评论
芬芬
芬芬

我不能说我完全理解您的方法背后的原因,但重要的是要考虑到您实质上声明的是:

FirstNumber = SecondNumber = Result = System.Int32;

Being that all these identities now refer to the same type, System.Int32. For that reason, visual studio is choosing to use the first author assigned allias to populate the intellisense.

当涉及到委托的声明时,请考虑您只需定义所需的签名即可,即“ IN和OUT”类型。最终被“包装” /“封装”的方法将提供参数的身份。

为了实现可读性,如果确实希望采用这种方式,请考虑使用所需的“可读”身份定义自己的委托类型:

public class FunctionPointers
{
    Operator Add;

     public FunctionPointers(Operator addOp)
     {
            Add = addOp;
     }       
}

public delegate Int32 Operator(Int32 FirstNumber, Int32 SecondNumber);

否则,采用“常规”方式,并带有方法上的标识:

Func<Int32,Int32,Int32> add;

public FunctionPointers()
{
    add = AddMethod;
}

public Int32 AddMethod(Int32 FirstNumber, Int32 SecondNumber)
{
    return FirstNumber + SecondNumber;
}

点赞
评论