C# 使用反射获取属性

C# 使用反射获取属性,c#,reflection,C#,Reflection,下面是我的Xaml.cs中的一个方法: void itemListView_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (this.UsingLogicalPageNavigation()) { this.navigationHelper.GoBackCommand.RaiseCanExecuteChanged()

下面是我的Xaml.cs中的一个方法:

void itemListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (this.UsingLogicalPageNavigation())
            {
                this.navigationHelper.GoBackCommand.RaiseCanExecuteChanged();
            }

            // Here is the object which properties i am trying to get:
            var mySelectedItem = e.AddedItems[0];

            //Here I would like to acess the properties

        }
我试图使用反射从我选择的项目中获取属性。 我一直在尝试这样的事情:

PropertyInfo property = GetType().GetProperty(propertyName) <--Cant resolve GetProperty()

PropertyInfo property=GetType().GetProperty(propertyName)您不需要对所需内容进行反射

将对象强制转换到正确的对象时,可以访问对象的属性

void itemListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (this.UsingLogicalPageNavigation())
        {
            this.navigationHelper.GoBackCommand.RaiseCanExecuteChanged();
        }
        var mySelectedItem = e.AddedItems[0];

        MyObject myObject = (MyObject)mySelectedItem;

        // Now you can access your property as follows: myObject.MyProperty;

    }

mySelectedItem.MyProperty是否有效?我没有投反对票,但你的问题不清楚问题出在哪里。会发生什么?确切的编译器或运行时异常(如果有)是什么?还有,你为什么还要使用反射?你确定你想要反射而不仅仅是投射吗?@DirkWrangler那么你应该像Matthew说的那样投射你的对象。@DirkWrangler你的投射方式如下:
MyObject myCastedObject=(MyObject)mySelectedItem
。我很惊讶你知道反射,但不知道铸造..这正是我需要的!只投了4张反对票@DirkWrangler我想这是因为你没有提出一个很好的问题。下次再加上更大的图片:)
void itemListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (this.UsingLogicalPageNavigation())
        {
            this.navigationHelper.GoBackCommand.RaiseCanExecuteChanged();
        }
        var mySelectedItem = e.AddedItems[0];

        MyObject myObject = (MyObject)mySelectedItem;

        // Now you can access your property as follows: myObject.MyProperty;

    }