I am trying to replicate .NET's Color struct
, which lets you call colors using Color.Black
, Color.White
etc. Here's my code:
struct Material
{
public string FilePath { get; set; }
public Material(string filepath) { FilePath = filepath; }
public static Material Sand
{
get
{
return new Material("images/sand");
}
}
public static Material Conrete
{
get
{
return new Material("images/conrete");
}
}
}
I'm getting an error saying I cannot use a constructor in a struct
. I am effectively copying from the .NET source code (Color.cs) and this is how it does it, although it doesn't use a constructor. The static properties do return a new Material()
however.
Full error message appearing on constructor CS0843 :
backing field for automatically implemented property must be fully assigned before it is returned to the caller
You can simply "chain" this()
, as in:
public Material(string filepath)
: this()
{
FilePath = filepath;
}
and this is the most common solution.
Of course you can do the same in other ways:
public Material(string filepath)
{
this = default(Material);
FilePath = filepath;
}
and
public Material(string filepath)
{
this = new Material { FilePath = filepath, };
}
and so on.
You CAN have a constructor, just not one with zero arguments.
However, isn't it clearer to write
new Material { FilePath = "images/concrete" }
instead of
new Material("images/concrete");
A custom constructor can always be bypassed by invoking the framework-provided parameterless constructor, so it can't be relied on for setting up invariants. And fields and properties can be set using member-initialization syntax. So struct constructors aren't terribly useful.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.