C# Static types cannot be used as parameters

前端 未结 8 2582
被撕碎了的回忆
被撕碎了的回忆 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();
    
        }
    
    0 讨论(0)
  • 2021-02-18 13:56

    It doesn't look like you even use that parameter in your method. You should just remove it because MediaTypeNames cannot be instantiated anyway.

    0 讨论(0)
提交回复
热议问题