将VB转换为C#错误应用程序.StartupPath
本文关键字:错误 应用程序 StartupPath VB 转换 | 更新日期: 2023-09-27 17:58:09
我从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
:上出错
系统。Windows。表格。应用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
将是一个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);
}
}