c# - 使用结构体字段作为参数

标签 c#

我有这门课。

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/

相关文章:

c# - 在 MVVM 菜单中绑定(bind) HeaderTemplate

c# - 如何将 Enum 转换为 Int 以用于 Expression.Equals 操作?

c# - Entity Framework 5 和 TPT 设计问题

c# - Xamarin App 仅在 Debug模式下崩溃

c# - C# 4 中的可选参数是否向后兼容?

c# - Entity Framework 是否具有 Linq2Sql 中 DataContext.GetTable<TEntity> 的等效项(ObjectContext.CreateQuery<T>?)

c# - 如何在不使用依赖注入(inject)的情况下实例化 ILoggerFactory?

c# - 如何使用 Identity Server 4 基于 Windows 身份验证颁发访问 token

c# - IdentityServer4 和 ASP.Net 身份 : Adding additional claims

c# - 正则表达式公式 - 无法识别公式