我想在Generic类中转换所有类,然后调用类方法

时间:2014-03-06 12:08:12

标签: c# generics

我想使用泛型来Proxy使用RealClient

public interface IClient
{
    string GetData();
}

public class RealClient : IClient
{
    string Data;
    public RealClient()
    {
        Console.WriteLine("Real Client: Initialized");
        Data = "success";
    }

    public string GetData()
    {
        return Data;
    }
}


public class Proxy : IClient
{
    RealClient _classobject = new RealClient();
    public Proxy()
    {
        Console.WriteLine("ProxyClient: Initialized");
    }

    public string GetData()
    {
        return _classobject.GetData();
    }
}


class Program
{
    static void Main(string[] args)
    {
        Proxy proxy = new Proxy();
        Console.WriteLine("Data from Proxy Client = {0}", proxy.GetData());

        Console.ReadKey();
    }
}

1 个答案:

答案 0 :(得分:2)

您似乎正在尝试实施Proxy design pattern,并希望您的代理可以使用任何类型的IClient

如果是这样,你不需要泛型。这是您通常用于实现代理的方法:

public class Proxy : IClient
{
    private readonly IClient _client;
    public Proxy(IClient client)
    {
        _client = client;
        Console.WriteLine("ProxyClient: Initialized");
    }

    public string GetData()
    {
        return _client.GetData();
    }
}

保持简单。