代码1
public class Human
{
private string h_name = "";
private string h_gender = "Male";
private int h_age = 0;
public string Name
{
get { return h_name; }
set { h_name = value; }
}
public string Gender
{
get { return h_name; }
set { h_name = value; }
}
public int Age
{
get { return h_age; }
set { h_age = value; }
}
}
代码2
public class Here
{
public static void Main(String[] args)
{
Human hm = new Human();
hm.Name = "Bill";
hm.Gender = "Male";
hm.Age = 20;
}
}
现在,我想将变量“hm”用作String,其中hm将返回Name属性...类似于:
string person = hm;
Console.WriteLine(person + " has greeted you!");
我该怎么办?我应该进行延期还是什么?
我重写了ToString()方法,是的,它适用于Console.WriteLine()
但是现在,我想将它作为字符串存储在字符串变量
中string person = hm;
Console.WriteLine(person);
我得到了这个
Cannot implicitly convert type 'Human' to 'string'
我也想在我的VB.NET程序中使用它,但是当我连接它时它给了我这个错误:
Operator '&' is not defined for types 'String' and 'Human'
答案 0 :(得分:5)
您可以使用operator overloading声明从您的类型到implicit
的{{1}}转换。但这是一个坏主意。我建议您在类中覆盖 string
方法,然后您可以像这样输出:
ToString
还有关于如何覆盖Console.WriteLine(hm + " has greeted you!");
方法
答案 1 :(得分:1)
通过将以下内容添加到Human
类中的隐式约定将起作用
public static implicit operator string(Human h)
{
return h.Name;
}
虽然我认为最好的方法是覆盖ToString
方法,如此
public override string ToString()
{
return Name;
}
答案 2 :(得分:0)
您可以覆盖ToString
方法:
public class Human
{
private string h_name = "";
private string h_gender = "Male";
private int h_age = 0;
public string Name
{
get { return h_name; }
set { h_name = value; }
}
public string Gender
{
get { return h_name; }
set { h_name = value; }
}
public int Age
{
get { return h_age; }
set { h_age = value; }
}
public override string ToString()
{
return Name;
}
}
答案 3 :(得分:0)
覆盖ToString()
方法。
public class Human
{
public override ToString() { return Name }
private string h_name = "";
private string h_gender = "Male";
private int h_age = 0;
public string Name
{
get { return h_name; }
set { h_name = value; }
}
public string Gender
{
get { return h_name; }
set { h_name = value; }
}
public int Age
{
get { return h_age; }
set { h_age = value; }
}
}
您的代码将如下所示:
Console.WriteLine(hm + " has greeted you!");
答案 4 :(得分:0)
vb.net
回答:
由其他人说明,您需要定义转化operator。如果要支持字符串连接,则还需要定义&
运算符。
Public Class Human
Public Property Name As String
Public Shared Widening Operator CType(value As Human) As String
Return value.Name
End Operator
Public Shared Operator &(left As Human, right As String) As String
Return (left.Name & right)
End Operator
Public Shared Operator &(left As String, right As Human) As String
Return (left & right.Name)
End Operator
Public Overrides Function ToString() As String
Return Me.Name
End Function
End Class