将VB转换为C#错误Application.StartupPath

时间:2014-04-13 08:11:04

标签: c# vb.net

我从VB转换代码:

Module Module1
    Public strPath = Application.StartupPath & "\"

    Public Sub LoadUserControl(ByVal obj As Object, ByVal uc As System.Windows.Forms.UserControl)
        obj.Controls.Clear()
        uc.Left = (obj.Width - uc.Width) / 2
        uc.Top = (obj.height - uc.Height) / 2 - 10
        obj.Controls.Add(uc)
    End Sub
End Module

到这个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'是一个属性,但像类型

一样使用

我该怎么做才能解决这个问题?

1 个答案:

答案 0 :(得分:0)

您可以使用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将是UserControl,那么您最好使用强类型,这将为您提供编译时安全性:

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);
    }
}