我有以下课程:
public class Notifications
{
public static Notifications Instance = new Notifications();
public NotificationHubClient Hub { get; set; }
private Notifications() {
Hub = NotificationHubClient.CreateClientFromConnectionString(
"<conn string with full access>", "<hub name>");
}
}
我试图修改代码以动态地将连接字符串和hub的名称的值传递给构造函数,我将构造函数更改为:
private Notifications(string connectionString,string hubName) {...}
我现在遇到的问题是Instance
,因为您可以注意到它调用的是没有参数的构造函数,我试图更改它但它没有工作:
public static Notifications Instance = new Notifications(
string connectionString,string hubName);
如何让Instance
调用构造函数并传递这两个参数?
答案 0 :(得分:2)
Instance
无权访问这些参数值 - 它必须为它们提供价值!
所以你可以这样做:
public static Notifications Instance = new Notifications("<conn string with full access>", "<hub name>");
答案 1 :(得分:1)
听起来你完全不需要Instance成员。您可能只是想使用一个非常普通的公共构造函数,然后可以传入参数。像这样:
public class Notifications
{
public NotificationHubClient Hub { get; set; }
public Notifications(string connString, string hubName) {
Hub = NotificationHubClient.CreateClientFromConnectionString(
connString, hubName);
}
}