首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >C#通过从Console.ReadLine返回的字符串引用属性

C#通过从Console.ReadLine返回的字符串引用属性
EN

Stack Overflow用户
提问于 2013-01-28 20:40:48
回答 4查看 729关注 0票数 1

我是C#的新手,在不断学习的过程中,我也在慢慢学习。在控制台应用程序中,我希望能够键入要显示的属性的名称。我偶然遇到的问题是,ReadLine将返回一个字符串,而我不知道如何将该字符串转换为对实际属性的引用。

我写了一个简单的例子来解释我想要做的事情。该示例现在将只输入它两次得到的任何输入。

我已经尝试过typeof(Person).GetProperty(property).GetValue().ToString(),但是我得到的是一条错误消息,告诉我GetValue没有使用0个参数的重载。

谢谢Rickard

代码语言:javascript
运行
复制
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();
        }
    }
}
EN

Stack Overflow用户

回答已采纳

发布于 2013-01-28 21:10:44

这将给你你正在寻找的东西。

代码语言:javascript
运行
复制
    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();
        }
    }
票数 0
EN
查看全部 4 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14562262

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档