C#编程中与结构中的构造方法有关的错误吗?!!! [英] Error related to Constructor Method in Structure in C# programming?!!!
问题描述
大家好
这是我的结构示例,我无法理解是否发生了错误!
Hi all
this is my example of Structure and i can''t understand Error happened!
struct Book
{
// Property
public string Author { get; set; }
public string Title { get; set; }
private int copyright;
public int Copyright
{
set
{
if (value < 2000)
Console.WriteLine("\n this copyright is not valid");
else
this.copyright = value;
}
get { return this.copyright; }
}
// Constructors
public Book(string a, string t, int c)
{
Author = a; // Error happened!
Title = t;
Copyright = c;
}
}
错误:在将控制权返回给调用者之前,必须完全分配自动实现的属性".Book.Author"的后备字段.考虑从构造函数初始值设定项调用默认构造函数.
Error: Backing field for automatically implemented property ''.Book.Author'' must be fully assigned before control is returned to the caller. Consider calling the default constructor from a constructor initializer.
推荐答案
看看该线程,它解释了问题和解决方法.
http: //stackstackflow.com/questions/1449871/what-is-happening-here-how-i-call-the-default-constructor-when-there-is-non [
Have a look at this thread, which explains the issues and a fix.
http://stackoverflow.com/questions/1449871/what-is-happening-here-how-can-i-call-the-default-constructor-when-there-is-non[^]
某种程度上,struct中的自动属性确实存在一些问题.
代替
Hi,
Somehow, automatic properties in struct do have some issue.
Instead of
public string Author { get; set; }
使用以下
use following
private int _Author ;
public int Author
{
get { return _Author ; }
set { _Author = value; }
}
请参阅 http://social.msdn.microsoft.com/Forums /en/vcsharpexpress2008prerelease/thread/31904232-e43b-455d-bd6a-c04c92c334ce [
See http://social.msdn.microsoft.com/Forums/en/vcsharpexpress2008prerelease/thread/31904232-e43b-455d-bd6a-c04c92c334ce[^] for more details.
Hope that helps, If it does, mark the answer as solution/upvote.
Thanks
Milind
问题是您的copyright
字段:
The problem is yourcopyright
field:
public Book(string a, string t, int c)
{
copyright = c;
Author = a;
Title = t;
Copyright = c;
}
将对其进行修复!
这篇关于C#编程中与结构中的构造方法有关的错误吗?!!!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!