如何解决抽象类继承的属性始终为空
我正在使用第三方服务,我的请求工作正常,但我需要将此结果传递给我的模型,以便我可以将其分成一个数组,并能够根据索引设置属性,因为它们没有有钥匙。我正在通过一个抽象类传递这个值并在我的模型中继承它,但是当试图在我的模型构造函数中调用该属性时,它总是返回 null,即使在我的抽象类中它已被设置。
我已经尝试使我的属性抽象和覆盖,但它不起作用。我也尝试通过构造函数传递值,但作为一个 T 实例,它不允许我,也许我做错了什么。
问题是,我可以通过什么方式获得值集?
这是我的 HttpBase.cs
public class HttpBase
{
public TResponse Post<TResponse>(string url,Dictionary<string,string> body)
where TResponse : ClassA,new()
{
string result = Post(url,body).Result.ToString();
TResponse response = new TResponse
{
JSON = result // this is where I try to set my property
};
return response;
}
public async Task<string> Post(string url,string> body)
{
// returns a string separated by '|'. Ex: "abc|abcd|abcde"
}
}
ClassA.cs
public abstract class ClassA
{
public string JSON { get; set; }
}
MyModel.cs
public class MyModel : ClassA
{
public MyObject()
{
string json = this.JSON; // null
string[] arr = json.Split('|','\n').ToArray(); // throws NullReferenceException
}
[Position(1)] //Custom Attribute
public string Name{ get; set; }
}
解决方法
快速回答是因为您过早地尝试使用 JSON 属性。
构造函数在初始化块之前执行,这意味着您还没有分配值。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。