我是C#的新手,在不断学习的过程中,我也在慢慢学习。在控制台应用程序中,我希望能够键入要显示的属性的名称。我偶然遇到的问题是,ReadLine将返回一个字符串,而我不知道如何将该字符串转换为对实际属性的引用。
我写了一个简单的例子来解释我想要做的事情。该示例现在将只输入它两次得到的任何输入。
我已经尝试过typeof(Person).GetProperty(property).GetValue().ToString(),但是我得到的是一条错误消息,告诉我GetValue没有使用0个参数的重载。
谢谢Rickard
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace AskingForHelp1
{
class Program
{
static void Main(string[] args)
{
Person p = new Person();
p.FirstName = "Mike";
p.LastName = "Smith";
p.Age = 33;
p.displayInfo(Console.ReadLine());
}
}
class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public UInt16 Age { get; set; }
public Person()
{
FirstName = "";
LastName = "";
Age = 0;
}
public void displayInfo(string property)
{
Console.WriteLine(property + ": " + property);
Console.ReadKey();
}
}
}发布于 2013-01-28 21:10:44
这将给你你正在寻找的东西。
static void Main(string[] args)
{
Person p = new Person();
p.FirstName = "Mike";
p.LastName = "Smith";
p.Age = 33;
Console.WriteLine("List of properties in the Person class");
foreach (var pInfo in typeof (Person).GetProperties())
{
Console.WriteLine("\t"+ pInfo.Name);
}
Console.WriteLine("Type in name of property for which you want to get the value and press enter.");
var property = Console.ReadLine();
p.displayInfo(property);
}
class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public UInt16 Age { get; set; }
public Person()
{
FirstName = "";
LastName = "";
Age = 0;
}
public void displayInfo(string property)
{
// Note this will throw an exception if property is null
Console.WriteLine(property + ": " + this.GetType().GetProperty(property).GetValue(this, null));
Console.ReadKey();
}
}https://stackoverflow.com/questions/14562262
复制相似问题