我想传递一个对象作为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;
}
答案 0 :(得分:10)
您可以使用重载方法:
public static HttpResponseMessage GenerateToken()
{
return GenerateToken(defUserInfo);
}
public static HttpResponseMessage GenerateToken<T>(T userInfo)
{
// stuff
return response;
}
答案 1 :(得分:1)
如果CustomerIdentifications
是一个结构,你可以通过使用struct属性而不是字段来模拟默认值:
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;
}
}