gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 21:54:18 27 4
gpt4 key购买 nike

我有这门课。

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

这可能吗?如果是,我应该怎么做。

最佳答案

你需要 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com