Reputation: 4555
I need function, that returns {obj type name}.{property name}.{property name}.. For example:
class City {
public string Name {get;set;}
}
class Country {
public string Name {get;set;}
public City MyCity {get;set;}
}
var myCountry = new Country() {
Name="Ukraine",
MyCity = new City() {
Name = "Kharkov"
}
}
So my function should return "{Country.Name}" or "{Country.MyCity.Name}" depends on input parameter. What is the way to do it?
Upvotes: 1
Views: 3651
Reputation: 2047
You didn't post much info on the requirement but, if you know your object type then there is no need to use Reflection, you can test with is
like this:
if(returnCity && myObject is Country) //I'm assuming that the input value is boolean but, you get the idea...
{
return myObject.City.Name;
}
else
{
return myObject.Name;
}
Now, if you want to use Reflection, you can do something among these lines:
public static string GetNameFrom( object myObject )
{
var t = myObject.GetType();
if( t == typeof(Country) )
{
return ((Country)myObject).City.Name;
}
return ((City)myObject).Name;
}
Or, a more generic approach:
static string GetNameFrom( object myObject )
{
var type = myObject.GetType();
var city = myObject.GetProperty( "City" );
if( city != null)
{
var cityVal = city.GetValue( myObject, null );
return (string)cityVal.GetType().GetProperty( "Name" ).GetValue( cityVal, null );
}
return (string)type.GetProperty( "Name" ).GetValue( myObject, null );
}
Upvotes: 0
Reputation: 7471
Create an IPrintable facade and use a recursive function Print(). Try to catch the idea and modify code for your concrete task. Hope, my example will be helpfull for you.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace StackOverflow
{
interface IPrintable
{
string Name { get; }
}
class City : IPrintable
{
public string Name { get; set; }
}
class Country : IPrintable
{
public string Name { get; set; }
public City MyCity { get; set; }
}
class Program
{
static void Main(string[] args)
{
var myCountry = new Country()
{
Name = "Ukraine",
MyCity = new City()
{
Name = "Kharkov"
}
};
Console.WriteLine(Print(myCountry, @"{{{0}}}"));
Console.WriteLine(Print(new City()
{
Name = "New-York"
}, @"{{{0}}}"));
}
private static string Print(IPrintable printaleObject, string formatter)
{
foreach (var prop in printaleObject.GetType().GetProperties())
{
object val = prop.GetValue(printaleObject, null);
if (val is IPrintable)
{
return String.Format(formatter, printaleObject.Name) + Print((IPrintable)val, formatter);
}
}
return String.Format(formatter, printaleObject.Name);
}
}
}
Upvotes: 0
Reputation: 6805
Use .net reflection
http://www.codersource.net/microsoftnet/cbasicstutorials/cnettutorialreflection.aspx
Upvotes: 2