调用自定义类的静态方法

New*_*per 3 powershell static-methods

我正在写一个脚本,它使用我自己的DLL:

[System.Reflection.Assembly]::LoadFile("E:\Group.School.dll")
Run Code Online (Sandbox Code Playgroud)

我想访问一个静态方法Student class.那个静态方法已经过载了.

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

    public static sting GetData(string fName, string lName)
    {
        ....
    }        
}
Run Code Online (Sandbox Code Playgroud)

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

$data = [Group.School.Student]::GetData
$data.Invoke("myId") 
Run Code Online (Sandbox Code Playgroud)

这给了我一个例外

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

Rom*_*min 6

原来代码中包含了几个错别字(例如Class,sting)和一个错误-类必须是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')
Run Code Online (Sandbox Code Playgroud)


Sha*_*evy 5

尝试:

[Group.School.Student]::GetData('myId')
Run Code Online (Sandbox Code Playgroud)