C# 如何在不重载的情况下强制用户在两种类型之一中输入方法参数的值

C# 如何在不重载的情况下强制用户在两种类型之一中输入方法参数的值,c#,parameters,C#,Parameters,我在做一个C项目,我有这个方法 private static Encryption_Model Enc(byte[] PlainData,byte[] Key) { //Some logic code here } 我希望用户以byte[]或int两种类型之一输入参数键 是否有任何方法可以强制用户在不使用重载的情况下在两种类型byte[]或int中的一种中输入键参数 非常感谢。不,重载就是为了这个。你为什么不想要呢 当然,您可以添加两个默认参数,并在

我在做一个C项目,我有这个方法

    private static Encryption_Model Enc(byte[] PlainData,byte[] Key)
    {

        //Some logic code here

    }
我希望用户以byte[]或int两种类型之一输入参数键

是否有任何方法可以强制用户在不使用重载的情况下在两种类型byte[]或int中的一种中输入键参数


非常感谢。不,重载就是为了这个。你为什么不想要呢

当然,您可以添加两个默认参数,并在两个参数都未提供或都未提供时抛出:

private static Encryption_Model Enc(byte[] plainData, byte[] keyBytes = null, int? keyInt = null)
{
    if ((keyBytes == null && keyInt == null) 
        || (keyBytes != null && keyInt != null))
    {
        throw new ArgumentException("Provide either keyBytes or keyInt");
    }
}
但这太糟糕了,因为现在你的方法必须去弄清楚提供了哪个参数以及如何使用它们,而这并不能保证编译时的安全性。这是:

private static Encryption_Model Enc(byte[] plainData, int key)
{
    var keyBytes = GetBytesFromInt(key); // Probably BitConverter.GetBytes()
    return Enc(plainData, keyBytes);
}

private static Encryption_Model Enc(byte[] plainData, byte[] key)
{
    // ...
}

不,重载就是为了这个。你为什么不想要呢

当然,您可以添加两个默认参数,并在两个参数都未提供或都未提供时抛出:

private static Encryption_Model Enc(byte[] plainData, byte[] keyBytes = null, int? keyInt = null)
{
    if ((keyBytes == null && keyInt == null) 
        || (keyBytes != null && keyInt != null))
    {
        throw new ArgumentException("Provide either keyBytes or keyInt");
    }
}
但这太糟糕了,因为现在你的方法必须去弄清楚提供了哪个参数以及如何使用它们,而这并不能保证编译时的安全性。这是:

private static Encryption_Model Enc(byte[] plainData, int key)
{
    var keyBytes = GetBytesFromInt(key); // Probably BitConverter.GetBytes()
    return Enc(plainData, keyBytes);
}

private static Encryption_Model Enc(byte[] plainData, byte[] key)
{
    // ...
}

您建议的第二个解决方案是感兴趣的,非常感谢您的时间,但这是一个负担过重的问题。你为什么认为你不想要这个?是的,我知道,我只是想忽略这个方法的许多重载,但是如果我没有找到任何不重载的解决方案,我会在最后使用重载,如果你有任何其他解决方案,我很感谢你,你建议的第二个解决方案是感兴趣的,非常感谢您的时间,先生,但这是一个超负荷。你为什么认为你不想要这个?是的,我知道,我只是想忽略这个方法的很多重载,但是如果我没有找到没有重载的任何解决方案,我会在最后使用重载,如果你有任何其他解决方案,我感谢你,先生