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

3

我希望将一个对象作为defUserInfo方法的默认值,但由于它不是一个编译时常量,所以这是不可能的。是否有其他方法可以使其正常工作?

private static CustomerIdentifications defUserInfo = new CustomerIdentifications
{
    CustomerID = "1010",
    UniqueIdentifier = "1234"
};
public static HttpResponseMessage GenerateToken<T>(T userInfo = defUserInfo)
{
   // stuff
    return response;
}
2个回答

10
您可以使用重载方法:
public static HttpResponseMessage GenerateToken()
{
    return GenerateToken(defUserInfo);
}
public static HttpResponseMessage GenerateToken<T>(T userInfo)
{
   // stuff
    return response;
}

2
我认为这是比使用魔法值更健壮的方法。 - vc 74

1
如果CustomerIdentifications是一个结构体,你可以使用结构体属性来模拟默认值,而不是使用字段:
using System;

struct CustomerIdentifications
{
    private string _customerID;
    private string _uniqueIdentifier;

    public CustomerIdentifications(string customerId, string uniqueId)
    {
      _customerID = customerId;
      _uniqueIdentifier = uniqueId;
    }

    public string CustomerID { get { return _customerID ?? "1010"; } }
    public string UniqueIdentifier { get { return _uniqueIdentifier ?? "1234"; } }
}

class App
{
  public static void Main()
  {
    var id = GenerateToken<CustomerIdentifications>();
    Console.WriteLine(id.CustomerID);
    Console.WriteLine(id.UniqueIdentifier);
  }

  public static T GenerateToken<T>(T userInfo = default(T))
  {
    // stuff
    return userInfo;
  }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接