. net c#方法和类型问题

本文关键字:类型 问题 方法 net | 更新日期: 2023-09-27 17:52:54

我正在努力解决这个问题。

我试图在另一个类中创建一个上下文菜单并将其链接到数据网格。下面是示例代码来重新创建我正在尝试做的事情:

  namespace Context_Menu_Test
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            ContextMenu cm = new ContextMenu();
            MenuItem mi1 = new MenuItem();
            mi1.Header = "Test1";
            cm.Items.Add(mi1);
            //This Works
            DG1.ContextMenu = cm;
            //THIS DOESN'T WORK
            DG1.ContextMenu = new Menus.Context_Menus.generate_datagrid_context_menu();
        }
    }
}
namespace Menus
{
    public class Context_Menus
    {
        public ContextMenu generate_datagrid_context_menu()
        {
            ContextMenu cm = new ContextMenu();
            MenuItem mi1 = new MenuItem();
            mi1.Header = "Test1";
            cm.Items.Add(mi1);
            return cm;
        }
    }
}

错误1 ' menu . context_menu .generate_datagrid_context_menu()'是一个'method',但被用作'type' W:'Test_Code'Context_Menu_Test'MainWindow.xaml.cs 33 55 Context_Menu_Test

. net c#方法和类型问题

正确的语法应该是:

DG1.ContextMenu = (new Menus.Context_Menus()).generate_datagrid_context_menu();

相当于:

var menu = new Menus.Context_Menus();
DG1.ContextMenu = menu.generate_datagrid_context_menu();

基本上你需要一个Context_Menus类的实例来调用一个非静态方法

generate_datagrid_context_menu是一个实例方法,因此您需要调用Menus.Context_Menus构造函数,然后在结果对象上调用generate_datagrid_context_menu:

var menus = new Menus.Context_Menus();
DG1.ContextMenu = menus.generate_datagrid_context_menu();
或者,您可以将generate_datagrid_context_menu方法设置为静态的:
public static ContextMenu generate_datagrid_context_menu()
{
    ...
}

然后像这样调用它:

DG1.ContextMenu = Menus.Context_Menus.generate_datagrid_context_menu();

文本菜单= new menu .文本菜单. generate_datagrid_文本菜单();

这一行实际上做了以下操作:

type = Menus.Context_Menus.generate_datagrid_context_menu;  
DG1.ContextMenu = new type();  

因为Menus.Context_Menus.generate_datagrid_context_menu();是一个方法而不是类型,所以编译器不会喜欢它。

var menus = new Menus.Context_Menus();
DG1.ContextMenu = menus.generate_datagrid_context_menu();

是你想要做的

如果您的类Context_Menus没有成员,您可以将其设置为静态

不要对静态类使用new !

public MainWindow()
{
    // ...
    DG1.ContextMenu = Menus.Context_Menus.generate_datagrid_context_menu();
}
namespace Menus
{
    public static class Context_Menus
    {
        public static ContextMenu generate_datagrid_context_menu()
        {
            ContextMenu cm = new ContextMenu();
            MenuItem mi1 = new MenuItem();
            mi1.Header = "Test1";
            cm.Items.Add(mi1);
            return cm;
        }
    }
}