Make class return a field

Pet*_*val 2 c# class

Is there a way to make a class return one of its fields by default like that:

public class TestClass
{
    public string something;
}

TestClass test = new TestClass();
test = "alpha"; // "alpha" string is assigned to "something"
Console.Write(test); // test returns "alpha" string from "something"
Run Code Online (Sandbox Code Playgroud)

How to make this work?

Ale*_*lex 5

对于所有那些说那是不可能的,)

public class TestClass
{
    public string something;

    public static implicit operator TestClass(string s) => new TestClass { something = s};

    public static implicit operator string(TestClass testClass) => testClass.something;
}
Run Code Online (Sandbox Code Playgroud)

用法:

TestClass test = new TestClass();
test = "alpha";
Console.WriteLine(test);
Run Code Online (Sandbox Code Playgroud)

给出:

alpha
Run Code Online (Sandbox Code Playgroud)

Console.WriteLine需要teststring并呼吁Console.WriteLine(string value)以隐式转换超载感谢。