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

问题描述 投票:0回答:1

这是常量类:

 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)

c# initialization uri
1个回答
1
投票

问题是2或URI在Constants中无效,阻止此类初始化属性。如果你更换它应该工作

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

© www.soinside.com 2019 - 2024. All rights reserved.