4

我有 4 种具有相似代码的方法

private void LogExceptions(ObjA.Input input, int customerId)
{
    //ObjA is a big object, thats why I try not to send the whole object in this method
    Log(input);
    Log(ObjA.Exceptions);
}

private void LogExceptions(ObjB.Input input, int customerId)
{
    //ObjB is a big object, thats why I try not to send the whole object in this method
    Log(input);
    Log(ObjB.Exceptions);
}

等等

我无法使其成为模板方法,例如

private void LogExceptions<T1,T2>(T1 input, int customerId) whereas     T1:ObjA.Input,ObjB.Input
{
    Log(T1);
    Log(T2);
}

怎么做或有其他方法吗?提前感谢任何帮助。

我不认为我的问题有助于获得正确的答案......这是确切的代码......

    private void LogExceptions(AccARef.Response response)
    {
        StringBuilder sbErrors = null;

        if (response.ValMethod != null && response.ValMethod.IsValid == false)
        {
            if (response.ValMethod.Errors.Count() > 0)
            {
                sbErrors = new StringBuilder();
                foreach (AccARef.Exception exp in response.ValMethod.Errors)
                {
                    sbErrors.Append(" * " + exp.Message + exp.StackTrace + " ");
                    Console.WriteLine(strError.ToString())
                }
            }
        }
    }

    private void LogExceptions(AccBRef.Response response)
    {
        StringBuilder sbErrors = null;

        if (response.ValMethod != null && response.ValMethod.IsValid == false)
        {
            if (response.ValMethod.Errors.Count() > 0)
            {
                sbErrors = new StringBuilder();
                foreach (AccBRef.Exception exp in response.ValMethod.Errors)
                {
                    sbErrors.Append(" * " + exp.Message + exp.StackTrace + " ");
                    Console.WriteLine(strError.ToString())
                }
            }
        }
    }

现在 AcctBRef 和 A​​cctARef 不能实现通用接口,因为它们不是我的对象。或者如果它们不是我的物品,我还能把它们装饰成我的吗?

4

3 回答 3

2

在这种情况下,您甚至不需要泛型,如果 ObjA 和 ObjB 要么继承自同一个基类或接口。

如果你有

interface IBaseClass 
{
   IEnumerable<Something> Exceptions {get;set;}
   InputType Input {get;set;}
}
class A : IBaseClass {}
class B : IBaseClass {}

您可以将其用于您的 LogExceptions 签名:

void LogExceptions(IBaseClass obj, int CustomerId) 
{
   Log(obj.Exceptions);
   Log(obj.Input);
}

如果他们从通用接口继承,那么我建议他们应该这样做。

于 2013-03-08T16:29:55.233 回答
0

What I feel is if there are 4 methods and they don't have same method signature its completely fine, it doesn't always have to be generic it has to be readable as well.

Why would you make 4 calls Log(T1),Log(T2),Log(T3),Log(T4) if all you have to do is Log(OneofTheTypeWhichYouKnowWhenCallingTheMethod).

Having said that you can always have reflection to play around like in your case.

于 2013-10-07T03:18:48.030 回答
0

您不能将 Type 参数传递给 Log 方法。您必须传递 Type 参数的实例。

尝试以下:

 private void LogExceptions<T1, T2>(T1 input, T2 exceptions, int customerId) 
    {
        Log(input);
        Log(exceptions);
    }
于 2013-03-08T16:40:27.380 回答