C# 未分配值/控制台读线
我是c语言的新手,我的代码中有一个问题。我的描述是未分配的,但是我以相同的方式分配的标题是可以的,运行良好。你能解释一下这是怎么可能的吗?我很抱歉,如果这是一个重复,我试图阅读了几个帖子,但找不到任何匹配的帖子C# 未分配值/控制台读线,c#,C#,我是c语言的新手,我的代码中有一个问题。我的描述是未分配的,但是我以相同的方式分配的标题是可以的,运行良好。你能解释一下这是怎么可能的吗?我很抱歉,如果这是一个重复,我试图阅读了几个帖子,但找不到任何匹配的帖子 namespace ExercisePost { public class Post { public string Title { get; set; } public string Description { get; set; }
namespace ExercisePost
{
public class Post
{
public string Title { get; set; }
public string Description { get; set; }
public DateTime CretationTime { get; set; }
public void SetTitle()
{
Console.WriteLine("Please, enter the title to your post ");
}
public void SetDescription()
{
Console.WriteLine("Please, enter the body to your post " );
}
public DateTime Publication()
{
CretationTime = DateTime.Now;
return CretationTime;
}
}
class Program
{
public static void Main(string[] args)
{
var post = new Post();
Console.WriteLine("Wanna share a post? If so please pres 'y' otherwise any key to cancel");
while(true)
{
var input = Console.ReadLine();
if (input == "y")
{
Console.Clear();
post.SetTitle();
string title = Console.ReadLine();
if (string.IsNullOrWhiteSpace(title))
{
post.SetTitle();
}
else
{
post.SetDescription();
string description = Console.ReadLine();
}
Console.WriteLine( title + description );
}
else
{
Console.WriteLine("GoodBye");
break;
}
}
}
}
}
当您初始化一个对象时,它会执行类的默认构造函数,在这种情况下,该构造函数将默认值赋值为null。您的描述有空值,这就是代码运行正常的原因。请在函数开头声明描述变量,而不是在函数中声明,如下图所示:
public static void Main(string[] args)
{
var post = new Post();
string description = ""; // variable declaration
Console.WriteLine("Wanna share a post? If so please pres 'y' otherwise any key to cancel");
while(true)
{
var input = Console.ReadLine();
if (input == "y")
{
Console.Clear();
post.SetTitle();
string title = Console.ReadLine();
if (string.IsNullOrWhiteSpace(title))
{
post.SetTitle();
}
else
{
post.SetDescription();
description = Console.ReadLine(); // variable assignment
}
Console.WriteLine( title + description );
}
else
{
Console.WriteLine("GoodBye");
break;
}
}
}
}
这段代码甚至不应该编译。。。