簡體   English   中英

將不穩定的默認參數傳遞給C#方法

[英]Passing an inconstant default parameter to a C# method

我想傳遞一個對象作為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;
}

您可以使用重載方法:

public static HttpResponseMessage GenerateToken()
{
    return GenerateToken(defUserInfo);
}
public static HttpResponseMessage GenerateToken<T>(T userInfo)
{
   // stuff
    return response;
}

如果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;
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM