BHere is the sample code, I've defined two classes. How can I use the Output
function to output the member which has the same name in two different classes?
class A
{
public string Name { get; set; }
public int Age { get; set; }
public string Email { get; set; }
public A(string name, int age, string email)
{
Name = name;
Age = age;
Email = email;
}
}
class B
{
public string Name { get; set; }
public int Age { get; set; }
public string Location { get; set; }
public B(string name, int age, string location)
{
Name = name;
Age = age;
Location = location;
}
}
void Output(object obj)
{
// How can I convert the object 'obj' to class A or class B
// in order to output its 'Name' and 'Age'
Console.WriteLine((A)obj.Name); // If I pass a class B in pararmeter, output error.
}
You'd have to either:
INamed
that has a string Name
property, that each of the two classes implementdynamic
and use it to access the Name
property (but in effect this is the same as #1, because the dynamic dispatch will merely use Reflection to get the Name
property).You can take advantage of dynamic
to bypass the compiler, it checks the type at runtime so you don't need to cast:
void Output(dynamic obj)
{
Console.WriteLine(obj.Name);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With