c# - 使用模板方法代替重复代码

标签 c# templates generics reusability

我有 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 不能实现公共(public)接口(interface),因为它们不是我的对象。或者如果它们不是我的东西,我还能把它们装饰成我的吗?

最佳答案

在这种情况下你甚至不需要泛型,如果 ObjA 和 ObjB 继承自相同的 base blass 或接口(interface)。

如果你有

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

如果它们继承自通用接口(interface),那么我建议它们应该继承。

关于c# - 使用模板方法代替重复代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15298553/

相关文章:

java - 不兼容的类型 : inference variable E#1 has incompatible upper bounds Enum<E#2>

c# - .NET 中的 JObject.SelectToken 等效项

c# - 为什么使用 Lockbits 编辑图像仍然需要 7 秒?

php - 创建用于呈现公共(public)页面的自定义模板

java - 从接口(interface)实现泛型方法而不困惑?

c# - 在工厂中使用通用接口(interface)时推断类型

c# - 从托管C#代码中调用非托管C++代码以生成脱机域加入Blob

c# - 手动更改类名后无法继承System.Window.Forms.Form类

html - 将值从模板传递到 django View

c++ - 对于在类外定义的友元函数,模板上的隐式转换查找失败