如何获取具有值的私有属性名称

时间:2013-12-15 09:22:35

标签: c# properties

无论如何我可以从另一个班级获得班级的私人财产吗? 这是我尝试过的。

class Program
{
    static void Main(string[] args)
    {
        Sample aSample = new Sample();
        //Is there anyway to access that Name private property here?
    }
}

class Sample
{
    private string Name { get; set; }
}

2 个答案:

答案 0 :(得分:2)

这里我尝试使用Reflection命名空间和PropertyInfo类。

如果您想要属性名称,请尝试使用它的值。但在这种情况下,您的财产应该是公开的。   它显示所有属性名称及其值

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace PropertiesImpConsoleApp
{
  class Student
  {
     //Declare variables
     string firstname;
     string lastname;

    //Define property for the variables
     public string FirstName
     {
         get
         {
             return firstname;
         }
         set
         {
             firstname = value;
         }
     }
     public string LastName
     {
         get
         {
             return lastname;
         }
         set
         {
             lastname = value;
         }
     }
  }
  class MyMain
  {
      public static void Main(string[] args)
      {
          Student aStudent = new Student();
          Console.WriteLine("Enter First Name");
          aStudent.FirstName = Console.ReadLine();
          Console.WriteLine("Enter LastName");
          aStudent.LastName = Console.ReadLine();

         //And to get the properties names you can do like this
          Dictionary<string, string> aDictionary = new Dictionary<string, string>();

          PropertyInfo[] allproperties = aStudent.GetType().GetProperties().ToArray();
          foreach (var aProp in allproperties)
          {
              aDictionary.Add(aProp.Name, aProp.GetValue(aStudent, null).ToString());
          }

          foreach (KeyValuePair<string, string> pair in aDictionary)
          {
              Console.WriteLine("{0}, {1}",
              pair.Key,
              pair.Value);
          }
          Console.ReadLine();
      }
   }
}

答案 1 :(得分:-2)

是的,公开。

私有意味着它只能在班级中访问

当您将其公开时,您可以从任何地方访问它

class Sample

{

public string Name {get;set;}

}