在不实例化类的情况下访问不同类同名空间中的方法

本文关键字:空间 方法 访问 实例化 情况下 同类 | 更新日期: 2023-09-27 18:08:21

是否可以访问具有相同名称空间的不同类中的方法

的示例代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WindowsFormsApplication1;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        public void Test()
        {
        }
    }
}

namespace WindowsFormsApplication1
{
    public class TestClass
    {
        public void Test2()
        {
        }
    }
}

我想在Test()方法中访问test2()方法,它们在不同的类中,但在相同的命名空间中,我想在不实例化TestClass类的情况下访问它,就像这样

TestClass test = new TestClass();
test.Test2();

我不想那样做,有办法吗?

注意" I am avoid to use a static Method"感谢您的回答

在不实例化类的情况下访问不同类同名空间中的方法

据我所知,没有办法做到。但是你为什么要这么做呢?

要访问Test(),您正在实例化一个类(Form1)。然后,您希望使用不同的方法,但不实例化类。那么运行它的意义是什么呢?它的背景是什么?

可能的解决方案:

  1. 创建一个扩展方法(因为你将扩展表单,我不建议这样做)
  2. 移动Test2()到Form1
  3. 移动test()到TestClass中,并且只实例化一次。
  4. 使用静态类