Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/299.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为指定的类名创建泛型方法_C#_Generics - Fatal编程技术网

C# 为指定的类名创建泛型方法

C# 为指定的类名创建泛型方法,c#,generics,C#,Generics,我想为指定的类创建泛型方法。伪代码可能如下所示: void doSend(Guid g) { //code } void doSend(Int32 i) { //code } void Send<T>(T param) where T:Guid or Int32 { //lots of code doSend(param) //lots of code } 我不想复制和粘贴整个实现,只更改一行 我不想复制和粘贴整个实现,只更改

我想为指定的类创建泛型方法。伪代码可能如下所示:

void doSend(Guid g)
{
   //code    
}
void doSend(Int32 i)
{
   //code     
}
void Send<T>(T param) where T:Guid or Int32
{
    //lots of code
    doSend(param) 
    //lots of code
}
我不想复制和粘贴整个实现,只更改一行

我不想复制和粘贴整个实现,只更改一行

那就不要。将所有公共代码移到一个或多个方法中,从入口点调用这些方法,并在调用方法中仅保留特定于Guid或int的实现:

void doSend(Guid g)
{
   //do stuff specific to `Guid`

   doSendCommon(g);   
}
void doSend(Int32 i)
{
   //do stuff specific to `int`

   doSendCommon(i);    
}

private void doSendCommon<T>(T value)
{
   // do stuff common to both
}

请注意,doSendCommon可以是完全泛型的,但由于它是私有的,所以您可以控制可以传入的类型。

您没有理由这样做吗

void Send(Guid param)
{
    ChunkA();
    doSend(param);
    ChunkB();
}

void Send(Int32 param)
{
    ChunkA();
    doSend(param);
    ChunkB();
}

void ChunkA()
{
  //lots of code
}

void ChunkB()
{
  //lots of code
}
另外,如果你只期望这两种类型。。。使用泛型将是一种轻微的滥用。您可能想后退一步,重新思考您的设计

编辑: 由于您在评论中提到,这些代码的共同点是日志记录和错误处理,因此我认为让sendforguid和Int32重载更有意义。您可以有一个更像这样的发送方法:

void Send(Guid param)
{
    try
    {
        LogSend(param);
        doSend(param);
    }
    catch (SendException e)
    {
        HandleSendException(e, param);
    }
}

拥有一个界面怎么样:

public interface IDoIt
{
    void DoIt();
}

public class Foo : IDoIt
{
    public void DoSomething()
    {

    }

    public void DoIt()
    {
        this.DoSomething();
    }
}

public class Bar : IDoIt
{
    public void DoSomethingElse()
    {

    }

    public void DoIt()
    {
        this.DoSomethingElse();
    }
}

public class GenericClass<T> where T: IDoIt, new ()
{
    public GenericClass()
    {
        T obj = new T();
        obj.DoIt();
    }
}

如果泛型不可能,则不可能在泛型中生成任何or。有多少代码可能与Guid和int数据类型相似?@DStanley所有日志记录、错误处理等。我认为抽象工厂模式解决了这个问题。检查