I have a class named Person
public class Person
{
string name;
int age;
SampleObject(string name, int age)
{
this.name = name;
this.age = age;
}
public override string ToString()
{
string s = age.ToString();
return "Person: " + name + " " + s;
}
}
I have overridden the ToString() to return the name of the person.
I am using the class in another class:
public class MyClass
{
public int Id {get;set;}
public Person person {get;set;}
}
Now, I want to access the class as
MyClass my = new MyClass();
I want that when I execute my.person
, it should return the ToString() value of the person class without explicitly calling the my.person.ToString()
Is it possible and if possible, how can I make this happen.
Thanks
You can create another readonly property
public string PersonName { get {return this.person.ToString();} }
Or add checking for possible null
public string PersonName
{
get
{
return (this.person == null) ? String.Empty : this.person.ToString();
}
}
Based on your comment about setting Name
of person by same property
I think approach with separated/specific property will be more maintainable
public string PersonName
{
get
{
return (this.person == null) ? String.Empty : this.person.ToString();
}
set
{
if(this.person == null)
{
this.person = new Person(value, 0);
}
else
{
this.person.Name = value;
}
}
}
I don't understand your question very well. but one of solutions to your question is to use implicit cast .
public class Person
{
string name;
int age;
public Person(string name, int age)
{
this.name = name;
this.age = age;
}
public override string ToString()
{
string s = age.ToString();
return "Person: " + name + " " + s;
}
// here
public static implicit operator string(Person d)
{
return d.ToString();
}
}
public class MyClass
{
public int Id { get; set; }
public Person Person { get; set; }
}
static void Main(string[] args)
{
var myclass = new MyClass();
myclass.Person = new Person("test", 12);
// use like this
string name = myclass.Person;
Console.WriteLine(name);
Console.WriteLine("Press any key to continue.");
Console.ReadLine();
}
You can achieve this with operator overload.
public static implicit operator string(Person p)
{
return p.ToString();
}
If you wish you can implement operator overload in MyClass to so it calls person as well.
public static implicit operator string(MyClass my)
{
return my.person;
}
With this you can do something like
string personString = my;
// or my.person if you only implement it for Person
Also you don't need to have a string variable for the age. Doing the following will work just fine.
return "Person: " + name + " " + age;
I would suggest to use string.Format though.
return string.Format("Person: {0} {1}", name, age);
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.