我希望能够做的是让一个结构返回一个变量,而不必通过它的属性来指定它。我可能错误地表述了这个问题,所以我将举一个例子(这当然失败了)。对于任何困惑或不一致之处,我深表歉意,但这就是我想要实现的目标,但不知道如何做到这一点,甚至不知道如何去寻找它。
struct theString{
public string my_String;
}
theString myString = new theString();
string currentMethod = myString.my_String;
string how_I_would_like_it = myString;
预先感谢您提供的任何/所有帮助。
[编辑] 属性字符串仅用于示例。您可以将字符串替换为您喜欢的任何内容,无论是 int、object、webhttprequest 等...
问题是当我执行字符串 how_I_would_like_it = myString; 时它不会将 my_String 变量分配给 how_I_would_like_it 并且出现无法隐式转换错误。
最佳答案
你可以这样做:
public class MyString
{
public static implicit operator string(MyString ms)
{
return "ploeh";
}
}
以下单元测试成功:
[TestMethod]
public void Test5()
{
MyString myString = new MyString();
string s = myString;
Assert.AreEqual("ploeh", s);
}
但总的来说,我不认为这是良好 API 设计的标志,因为我更喜欢明确性而不是惊喜...但话又说回来,我不知道上下文问题...
关于C#:结构体返回没有属性的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1907176/