简体   繁体   English

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

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

I want to pass an object as the default value for defUserInfo method, but It's not possible since it's not a compile-time constant . 我想传递一个对象作为defUserInfo方法的默认值,但它不可能,因为它不是compile-time constant Is there any other way to make this work? 有没有其他方法可以使这项工作?

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

You could use an overloaded method: 您可以使用重载方法:

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

If CustomerIdentifications were a struct, you could kind of simulate default values, by using struct properties instead of fields: 如果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