如何在类方法中获取类本身的属性值

问题描述 投票:0回答:1

我想创建一些类,它们必须具有某种外观(如我的示例中所示的方式)。

一些类属性本身就是类(或结构)。

我想在我的类中编写一个方法,获取所有结构体属性的属性值并将它们写入字符串。

这就是我的课程的样子:

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
};

如何创建一个工作方法来获取这些属性?

c# class inner-classes
1个回答
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();
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.