Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
330 views
in Technique[技术] by (71.8m points)

c# - Python for .NET: How to call a method of a static class using Reflection?

I want to use a method of a static class.

This is my C# code:

namespace SomeNamepace
{
    public struct SomeStruct
    {
        ....
    }

    public static class SomeClass
    {
        public static double SomeMethod
        {
            ....
        }

    }

If it was a "normal" class I could use SomeMethod like

lib = clr.AddReference('c:\TestModule.dll')
from System import Type
type1 = lib.GetType('SomeNamespace.SomeClass')
constructor1 = type1.GetConstructor(Type.EmptyTypes)  
my_instance = constructor1.Invoke([])  
my_instance.SomeMethod() 

But when trying to do this with the static class I get

MissingMethodException: "Cannot create an abstract class.

How could I solve this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Thanks to the comments to the question I was able to find a solution using MethodBase.Invoke (Object,?Object[])

lib = clr.AddReference('c:\TestModule.dll')
from System import Type
my_type = lib.GetType('SomeNamespace.SomeClass')
method = my_type.GetMethod('SomeMethod')  

# RetType is void in my case, so None works
RetType = None
# parameters passed to the functions need to be a list
method.Invoke(RetType, [param1, param2])  

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...