调用自定义类的静态方法

时间:2013-08-01 09:02:34

标签: powershell static-methods

我正在编写一个脚本,其中使用了我自己的DLL:

[System.Reflection.Assembly]::LoadFile("E:\Group.School.dll")

我想在Student class中访问静态方法。那个静态方法已经过载了。

Class Student
{        
    public static sting GetData(string id)
    {
        ....
    }

    public static sting GetData(string fName, string lName)
    {
        ....
    }        
}

从PowerShell我将访问第一种方法,如下所示:

$data = [Group.School.Student]::GetData
$data.Invoke("myId") 

这给了我一个例外

  

使用“1”参数调用“Invoke”的异常:“使用”1“参数调用”GetData“的异常:”对象引用未设置为对象的实例。“”

3 个答案:

答案 0 :(得分:6)

原始代码包含一些拼写错误(例如Classsting)和错误 - 该类必须为public

这是经过纠正的代码,可以正常运行:

# the corrected code added inline (might be in a DLL, as well):
Add-Type @'
public class Student
{
    public static string GetData(string id)
    {
        return "data1";
    }

    public static string GetData(string fName, string lName)
    {
        return "data2";
    }
}
'@

# call the static method:
[Student]::GetData('myId')

答案 1 :(得分:3)

尝试:

[Group.School.Student]::GetData('myId')

答案 2 :(得分:0)

确保包含Student类的dll未使用Visual Studio中的“任何CPU”选项进行编译,请尝试为x86编译它。

相关问题