如何在类方法中获得属于类本身值的属性
问题描述:
我想创建一些类,必须以某种方式查看(以我的示例中显示的方式)。 某些类属性本身就是类(或结构体)。 我想在我的类中编写一个方法,该方法获取所有属性的属性值,即结构并将它们写入字符串。如何在类方法中获得属于类本身值的属性
因此,这是我的课是这样的:
public class car
{
public string brand { get; set; }
public tire _id { get; set; }
public string GetAttributes()
{
Type type = this.GetType();
PropertyInfo[] properties = type.GetProperties();
foreach(PropertyInfo propertyInfo in properties)
if (propertyInfo.PropertyType.ToString().Contains("_"))
{
//I want to write the actual value of the property here!
string nested_property_value = ...
return nested_property_value;
}
}
}
这是我的结构是这样的:
public struct tire
{
public int id { get; set; }
}
这将是主程序:
tire mynewtire = new tire()
{
id = 5
};
car mynewcar = new car()
{
_id = mynewtire
};
任何人有一个想法如何创建GetAttributes-Methode?我一直试图弄清楚现在这个年龄,但不去那里...
答
这段代码会让你开始。我建议你看看其他的序列化方法(如JSON)。
using System;
namespace Test
{
public class car
{
public string brand { get; set; }
public tire _id { get; set; }
public string GetAttributes()
{
var type = this.GetType();
var returnValue = "";
var properties = type.GetProperties();
foreach (var propertyInfo in properties)
{
// Look at properties of the car
if (propertyInfo.Name.Contains("_") && propertyInfo.PropertyType.IsValueType &&
!propertyInfo.PropertyType.IsPrimitive)
{
var propValue = propertyInfo.GetValue(this);
var propType = propValue.GetType();
var propProperties = propType.GetProperties();
foreach (var propPropertyInfo in propProperties)
{
// Now get the properties of tire
// Here I just concatenate to a string - you can tweak this
returnValue += propPropertyInfo.GetValue(propValue).ToString();
}
}
}
return returnValue;
}
}
public struct tire
{
public int id { get; set; }
}
public class Program
{
static void Main(string[] args)
{
var mynewtire = new tire()
{
id = 5
};
var mynewcar = new car()
{
_id = mynewtire
};
Console.WriteLine(mynewcar.GetAttributes());
Console.ReadLine();
}
}
}
+0
欢呼的伴侣,解决了我的问题!真的很感谢你花时间帮助我!正如我所说,我刚刚开始编写两个月前,所以我不知道csharp所提供的所有可能性!我也会研究你建议的其他方法。 – FlixFix
您的类型没有任何属性或属性。 – Servy
这是一个求职面试问题吗? –
您是否考虑使用JSON序列化将其转换为字符串? https://stackoverflow.com/questions/15843446/c-sharp-to-json-serialization-using-json-net – mjwills