2015-10-19 100 views
2

我有这个类。使用struct字段作为参数

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,我想限制他们只使用定义AttachmentFormats之一。像

EmailManager.SendEmail("xxx","yy",EmailManager.AttachmentFormats.Excel); 

这是可能的。如果是的话,我该怎么做。

+3

定义枚举,而不是struct。 –

+0

然后,该值将是一个int,然后我必须再次写入扩展方法。对。我认为这会更简单。 – Qwerty

+0

int !!为什么?你将会在你的问题“EmailManager.AttachmentFormats.Excel”中提到你的价值。为了提供有限的选项,我觉得枚举是最好的选择。也在sendEmail()你想得到“.xlsx”? –

回答

3

你需要enumstruct

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; 
     } 
    } 
} 

其他解决方案是创建接口和类实现这个接口:

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 
    } 
+0

我会这样做。但是这些值必须在int中,然后在某处再次使用某个逻辑来将这些值与字符串匹配。在struct /或enum中直接使用字符串值会更简单 – Qwerty

+0

@Qwerty添加了另一种更适合您需求的解决方案 – Fabjan

+0

猜测这不适用于struct,另一种简单的方法是enum。使用接口看起来比enum更复杂,代码更多。感谢你,虽然 – Qwerty

0

如果您希望您班级的用户致电SendEmail,那么它将不得不公开。

此外,我回声使用枚举而不是结构的早期评论。通过上面的Aram Kocharyan给出的实现,用户可以使用预定义的字符串,但不会被强制使用。没有什么阻止他们呼吁:

EmailManager.SendEmail("me","you","Any old string I can make up"); 

使用枚举法:

EmailManager.SendEmail("me","you",EmailManager.AttachmentFormat.Excel); 
相关问题