将不稳定的默认参数传递给C#方法

Yar*_*Yar 3 .net c# parameters

我想传递一个对象作为defUserInfo方法的默认值,但它不可能,因为它不是一个compile-time constant.有没有其他方法可以使这项工作?

private static CustomerIdentifications defUserInfo = new CustomerIdentifications
{
    CustomerID = "1010",
    UniqueIdentifier = "1234"
};
public static HttpResponseMessage GenerateToken<T>(T userInfo = defUserInfo)
{
   // stuff
    return response;
}
Run Code Online (Sandbox Code Playgroud)

Ren*_*ogt 10

您可以使用重载方法:

public static HttpResponseMessage GenerateToken()
{
    return GenerateToken(defUserInfo);
}
public static HttpResponseMessage GenerateToken<T>(T userInfo)
{
   // stuff
    return response;
}
Run Code Online (Sandbox Code Playgroud)

  • 我认为这比使用魔术值更有效 (2认同)