如何将变量分配给类

时间:2018-08-29 11:07:43

标签: c# class inheritance uwp

我陷入了问题,可以寻求帮助。所以这大概是我的代码:

from flask_migrate import Migrate
migrate = Migrate(app, db) 

现在,我的问题是MyMenuFlyoutItem类中的“视图”向我抛出错误。怎样才能使MyMenuFlyout类从x.cs中获取dataPackage.SetText(view.vSelGetText());的视图? 错误为:“非静态字段,方法或属性x.view需要对象引用”

1 个答案:

答案 0 :(得分:2)

您无法从view类的实例方法访问ReaderPage类的非静态字段MyMenuFlyoutItem。尽管MyMenuFlyoutItemReaderPage的{​​{3}}和/或在同一个文件中声明的,但这些类及其实例彼此完全独立。可以认为好像MyMenuFlyoutItem没有被声明为嵌套的一样:

public sealed partial class ReaderPage : Page, View.Listener
{
    private View view;
}

class MyMenuFlyoutItem : MenuFlyoutItem
{
    private void MyMenuFlyoutItem_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
    {
        var dataPackage = new DataPackage();
        // cannot access view
        dataPackage.SetText(view.vSelGetText());
        Clipboard.SetContent(dataPackage);
    }
}

从以上显而易见,MyMenuFlyoutItem需要某个ReaderPage实例才能访问它的view,因为可能有ReaderPage类的许多实例,并且编译器会不知道,应该从这些实例中的哪个view进行读取。嵌套类的优点是可以“查看”父类的 private 成员,但仍然需要引用ReaderPage,并希望从中引用view可供阅读。

对此问题的几种可能解决方案之一是将ReaderPage类的引用传递给MyMenuFlyoutItem构造函数:

public sealed partial class ReaderPage : Page, View.Listener
{
    // Nested class can access this field despite being declared as private
    private View view;

    class MyMenuFlyoutItem : MenuFlyoutItem
    {
        private ReaderPage page;

        MyMenuFlyoutItem(ReaderPage page)
        {
            this.page = page;
        }

        public MyMenuFlyoutItem()
        {
            this.Click += MyMenuFlyoutItem_Click;
        }

        private void MyMenuFlyoutItem_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            var dataPackage = new DataPackage();
            // Nested class can access field `view` of parent class, although `view` is declared private
            // but you still need `page` reference
            dataPackage.SetText(page.view.vSelGetText());
            Clipboard.SetContent(dataPackage);
        }
    }
}