Tom*_*len 18 c# asp.net static types
public static void SendEmail(String from, String To, String Subject, String HTML, String AttachmentPath = null, String AttachmentName = null, MediaTypeNames AttachmentType = null)
{
....
// Add an attachment if required
if (AttachmentPath != null)
{
var ct = new ContentType(MediaTypeNames.Text.Plain);
using (var a = new Attachment(AttachmentPath, ct)
{
Name = AttachmentName,
NameEncoding = Encoding.UTF8,
TransferEncoding = TransferEncoding.Base64
})
{
mailMessage.Attachments.Add(a);
}
}
....
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的那样MediaTypeNames AttachmentType抛出错误:
'System.Net.Mime.MediaTypeNames': static types cannot be used as parameters
Run Code Online (Sandbox Code Playgroud)
处理这个问题的最佳方法是什么?
不建议这样做,但您可以模拟使用静态类作为参数.像这样创建一个Instance类:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
然后你的函数将使用静态类:
private static void YourFunction(Instance instance)
{
instance.Call("TheNameOfMethodToCall", null);
}
Run Code Online (Sandbox Code Playgroud)
例如.电话:
并使用这样的:
static void Main(string[] args)
{
YourFunction(new Instance(typeof(YourStaticClass)));
Console.ReadKey();
}
Run Code Online (Sandbox Code Playgroud)