C# Static types cannot be used as parameters

前端 未结 8 2584
被撕碎了的回忆
被撕碎了的回忆 2021-02-18 13:22
public static void SendEmail(String from, String To, String Subject, String HTML, String AttachmentPath = null, String AttachmentName = null, MediaTypeNames AttachmentTy         


        
8条回答
  •  不思量自难忘°
    2021-02-18 13:54

    It's not recommended but you can simulate use of Static classes as parameters. Create an Instance class like this :

    public class Instance
    {
    
        public Type StaticObject { get; private set; }
    
        public Instance(Type staticType)
        {
            StaticObject = staticType;
        }
    
        public object Call(string name, params object[] parameters)
        {
            MethodInfo method = StaticObject.GetMethod(name);
            return method.Invoke(StaticObject, parameters);
        }
    
        public object Call(string name)
        {
            return Call(name, null);
        }
    
    }
    

    Then your function where you would use the static class :

        private static void YourFunction(Instance instance)
        {
            instance.Call("TheNameOfMethodToCall", null);
        }
    

    For instance.Call :

    • The first parameter is the name of the method of your static class to call
    • The second parameter is the list of arguments to pass to the method.

    And use like this :

        static void Main(string[] args)
        {
    
            YourFunction(new Instance(typeof(YourStaticClass)));
    
            Console.ReadKey();
    
        }
    

提交回复
热议问题