我想创建一些必须以某种方式查看的类(我的示例中显示的方式)。 一些类属性本身就是类(或结构)。 我想在我的类中编写一个方法来获取所有属性的属性值,即Structs并将它们写入字符串。
所以这就是我的课程:
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?我现在已经试图解决这个问题很多年了,但是没有到达那里......
答案 0 :(得分:0)
此代码将帮助您入门。我建议您查看其他序列化方法(例如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();
}
}
}