C# 按变量名调用时返回预期值
我想创建一个结构,当它的值被设置时,您可以通过变量名调用该值C# 按变量名调用时返回预期值,c#,struct,C#,Struct,我想创建一个结构,当它的值被设置时,您可以通过变量名调用该值 struct A { int Value; } Main() { // Sets Value to 9 A Number = 9; Console.Write(Number); // output should be 9 } 我希望输出为9,您的结构未命中值的访问器 您可以像这样优化代码: struct A { public int Value; pu
struct A
{
int Value;
}
Main()
{
// Sets Value to 9
A Number = 9;
Console.Write(Number);
// output should be 9
}
我希望输出为9,您的结构未命中值的访问器
您可以像这样优化代码:
struct A
{
public int Value;
public A(int val)
{
Value = val;
}
public override string ToString()
{
return Value.ToString();
}
}
并根据需要使用:
// Sets Value to 9
A Number = new A(9);
Console.Write(Number);
准确地使用你写的数字=9;Console.WriteNumber;首先需要定义隐式赋值运算符,然后需要重写ToString方法以获得正确的输出。示例代码:
struct A
{
public int Value;
public A(int value)
{
Value = value;
}
// This allows creating an instance of struct A by writing it as an assignment statement
static public implicit operator A(int value)
{
return new A(value);
}
public override string ToString()
{
return Value.ToString();
}
}
public static void Main()
{
A Number = 9;
Console.Write(Number);
}
现场演示:除了Peter B的答案之外,您还可以定义相反的隐式转换,而不是ToString
您的代码可以工作,但您的解释是不正确的:结构可以同时包含字段和属性,而字段没有访问器,或者没有访问器,它们将是属性。
struct A
{
public int Value;
public A(int value)
{
Value = value;
}
// This allows creating an instance of struct A by writing it as an assignment statement
static public implicit operator A(int value)
{
return new A(value);
}
public override string ToString()
{
return Value.ToString();
}
}
public static void Main()
{
A Number = 9;
Console.Write(Number);
}
public static implicit operator int(A a)
{
return a.Value;
}