我有这门课。
public class EmailManager
{
public struct AttachmentFormats
{
public const string Excel = ".xlsx";
public const string Pdf = ".pdf";
}
private static bool SendEmail(string to, string from, ???)
{
/*??? is one of the AttachmentFormats*/
}
}
当用户想要使用SendEmail
时,我想限制他们仅使用定义的附件格式之一。喜欢
EmailManager.SendEmail("xxx","yy",EmailManager.AttachmentFormats.Excel);
这可能吗。如果是的话我该怎么办。
最佳答案
您需要enum
而不是struct
:
public enum AttachmentFormat
{
xlsx = 0,
pdf = 1
}
public class EmailManager
{
private static bool SendEmail(string to, string @from, AttachmentFormat format)
{
switch(format)
{
case AttachmentFormat.pdf:
// logic
break;
case AttachmentFormat.xlsx:
// logic
break;
}
}
}
其他解决方案是创建接口(interface)和实现该接口(interface)的类:
public interface IAttachmentFormat {}
public sealed class PDFAttachmentFormat : IAttachmentFormat { }
public sealed class XLSXAttachmentFormat : IAttachmentFormat { }
然后检查 SendEmail 方法内的类型:
private static bool SendEmail(string to, string @from, IAttachmentFormat format)
{
if(format is PDFAttachmentFormat) // some logic for pdf
if(format is XLSXAttachmentFormat) // some logic for xlsx
}
关于c# - 使用结构体字段作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33208168/