如何解决“字段X永远不会分配给它,并且其默认值将为null”? [英] How to fix "Field X is never assigned to and will have its default value null"?
问题描述
我正在尝试从控制台(街道,城市,国家/地区)输入输入,但这些字段带有下划线并显示消息(该字段从未分配给该字段,并且其值将为null)。我还创建了一个不起作用的方法SetFullAddress(如果是因为该消息,则为idk)。
I am trying to enter input from the console(street, city, country) but the fields are underlined and display the message(field is never assigned to and will have its value null). I have also created a method SetFullAddress which doesn't work(idk if it is because of that message).
Address类中的代码:
Code inside Address class:
public class Address
{
private string street;
private string city;
private string country;
public Address()
{
this.Street = street;
this.City = city;
this.Country = country;
}
public string Street { get; set; }
public string City { get; set; }
public string Country { get; set; }
public string SetFullAddress()
{
return ($"Full address: {street} {city} {country}");
}
public void DisplayAddress()
{
Console.WriteLine($"Street: {Street}");
Console.WriteLine($"City: {City}");
Console.WriteLine($"Country: {Country}");
Console.WriteLine(SetFullAddress());
}
}
在Main方法内:
Address address = new Address();
Console.Write("Street: ");
address.Street = Console.ReadLine();
Console.Write("City: ");
address.City = Console.ReadLine();
Console.Write("Country: ");
address.Country = Console.ReadLine();
Console.WriteLine();
address.DisplayAddress();
推荐答案
如果您没有遇到任何错误并且只是想要从该脚本中禁用警告,您可以使用 #pragma warning disable 0649
If you're not encountering any errors and just want to disable the warnings from that script you caa use #pragma warning disable 0649
但是请不要滥用它,这些警告可能会在以后对您有所帮助。
But don't abuse it, these warnings may help you later.
这篇关于如何解决“字段X永远不会分配给它,并且其默认值将为null”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!