为什么不能使用静态只读对象属性?

时间:2019-03-29 13:31:13

标签: c# initialization uri

这是常量类:

 public static class Constants
    {
        public const string USER_ID = "conduent";
        public const string PASSWORD = "593becd1-02f6-46f0-bf34-25b393ad041b";
        public static readonly Uri BASE_URI = new Uri("https://staging.test-476b.com");
        public static readonly Uri GET_TOKEN_URI = new Uri("api/session");
        public static readonly Uri SEND_CASE_URI = new Uri("api/referral_request");
    }

这是用法

public class DanestreetHttp
    {

        private AuthToken authToken = null;

        private readonly HttpClient httpClient = new HttpClient()
        {
            BaseAddress = Constants.BASE_URI
        };
}

在屏幕快照上,您可以看到错误,该错误在我将BaseAddress = Constants.BASE_URI更改为BaseAddress = new System.Uri("https://staging.test-476b.com")之后消失了。静态只读初始化有什么问题?

屏幕

Image 2

PS。我当前的解决方案:BaseAddress = new Uri(Constants.BaseAddress)

1 个答案:

答案 0 :(得分:1)

问题在于Constants中2或URI无效,从而阻止了此类初始化属性。如果您替换

,它应该可以工作
public static readonly Uri GET_TOKEN_URI = new Uri("api/session");
public static readonly Uri SEND_CASE_URI = new Uri("api/referral_request");

使用

public static readonly Uri GET_TOKEN_URI = new Uri("http://api/session");
public static readonly Uri SEND_CASE_URI = new Uri("http://api/referral_request");

(或https)

Fiddle