C# 将VB转换为C错误应用程序.StartupPath

C# 将VB转换为C错误应用程序.StartupPath,c#,vb.net,C#,Vb.net,我从VB转换了代码: 模块1 公共strPath=Application.StartupPath&\ 公共子加载UserControlByVal obj作为对象,ByVal uc作为System.Windows.Forms.UserControl obj.Controls.Clear uc.Left=目标宽度-uc.宽度/2 uc.Top=目标高度-uc.height/2-10 对象控制 端接头 端模块 对于此C代码: static class Module1 { public stat

我从VB转换了代码:

模块1 公共strPath=Application.StartupPath&\ 公共子加载UserControlByVal obj作为对象,ByVal uc作为System.Windows.Forms.UserControl obj.Controls.Clear uc.Left=目标宽度-uc.宽度/2 uc.Top=目标高度-uc.height/2-10 对象控制 端接头 端模块 对于此C代码:

static class Module1
{
    public static  strPath = Application.StartupPath + "\\";

    public static void LoadUserControl(object obj, System.Windows.Forms.UserControl uc)
    {
        obj.Controls.Clear();
        uc.Left = (obj.Width - uc.Width) / 2;
        uc.Top = (obj.height - uc.Height) / 2 - 10;
        obj.Controls.Add(uc);
    }
}
我在strPath上出错:

System.Windows.Forms.Application.StartupPath'是一个属性,但与类型一样使用

我能做些什么来解决这个问题

您可以使用C中的dynamic关键字来模拟VB的弱类型:

static class Module1
{
    public static string strPath = System.Windows.Forms.Application.StartupPath + "\\";

    public static void LoadUserControl(dynamic obj, System.Windows.Forms.UserControl uc)
    {
        obj.Controls.Clear();
        uc.Left = (obj.Width - uc.Width) / 2;
        uc.Top = (obj.Height - uc.Height) / 2 - 10;
        obj.Controls.Add(uc);
    }
}
在本例中,obj变量被声明为动态变量,以便允许在运行时调用属性和方法。还要注意,您应该为strPath静态变量提供一个类型,在本例中为string

或者,如果您知道obj将是一个用户控件,则最好使用强类型,这将为您提供编译时安全性:

static class Module1
{
    public static string strPath = System.Windows.Forms.Application.StartupPath + "\\";

    public static void LoadUserControl(System.Windows.Forms.UserControl obj, System.Windows.Forms.UserControl uc)
    {
        obj.Controls.Clear();
        uc.Left = (obj.Width - uc.Width) / 2;
        uc.Top = (obj.Height - uc.Height) / 2 - 10;
        obj.Controls.Add(uc);
    }
}

若在我的项目中,我并没有使用UserCtrol,而是只使用表单,那个么如何修复代码呢?public static void LoadUserControlSystem.Windows.Forms.UserControl obj,System.Windows.Forms.UserControl uc{obj.Controls.Clear;uc.Left=obj.Width-uc.Width/2;uc.Top=obj.Height-uc.Height/2-10;obj.Controls.Encluco;}您尚未提供“strPath”的类型。最初的VB代码隐式地使用“Object”作为类型-您需要在C中显式地执行此操作,并且不能使用“var”,因为它仅用于局部变量。