首页 新闻 赞助 找找看

传递参数类型时该如何处理

0
悬赏园豆:10 [已解决问题] 解决于 2018-03-06 11:29

我想使用一个接口,每个继承此接口的类的传入的参数类型不同,此时该如何处理为好啊?

 

    public interface IComm
    {
        bool IConn(c);
    }

    public class ComConfig
    {
        public int p;
        public int timeout;
    }
    public class Com :IComm
    {      
        public bool IConn(ComConfig c) 
        {
            return true;        
        }    
    }

    public class LanConfig
    {
        public string ip;
        public int port;
    }
    public class Lan : IComm
    {
        public bool IConn(LanConfig c)
        {
            return true;
        }
    }

 

之前我是想使用泛型来处理,但是好像也不行,我觉得应该有方法实现吧?
请各位大神帮帮忙!

明爷的主页 明爷 | 初学一级 | 园豆:9
提问于:2018-03-05 17:15
< >
分享
最佳答案
0
using System;
using System.Text;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            Com com = new Com();
            Lan lan = new Lan();
            if(com.Iconn(new ComConfig())==true)
            {
                Console.WriteLine("ok");
            }
            if(lan.Iconn(new LanConfig())==true)
            {
                Console.WriteLine("OK");
            }
        }
    }

    public interface Icomm
    {
         bool Iconn<T>(T c);

    }

    public class ComConfig
    {
        public int p;
        public int timeout;
    }

    public class Com : Icomm
    {
        public  bool Iconn<ComConfig>(ComConfig c)
        {
            return true;
        }
    }

    public class LanConfig
    {
        public string ip;
        public int port;
    }
    public class Lan : Icomm
    {
        public bool Iconn<LanConfig>(LanConfig c)
        {
            return true;
        }
    }
}

用c#写的。

收获园豆:10
Shendu.CC | 老鸟四级 |园豆:2138 | 2018-03-05 18:20

谢谢!

明爷 | 园豆:9 (初学一级) | 2018-03-06 11:29

@明爷: 我也谢谢你,我都没豆子了。感谢你的10个豆子!

Shendu.CC | 园豆:2138 (老鸟四级) | 2018-03-06 11:34

@Shendu.cc: 

呵呵,我还有个问题,在调用者的角度,参数类型的不同,还是很麻烦,还能将参数进行抽象成接口的方式吗?

明爷 | 园豆:9 (初学一级) | 2018-03-06 19:43

@明爷: em...你再阐述一波。你是指把LanConfig和ComConfig抽象成一个接口,给调用者统一使用吗、?

Shendu.CC | 园豆:2138 (老鸟四级) | 2018-03-06 20:43
其他回答(2)
0

泛型+基类约束

https://github.com/wrx362114/EasyMQService/blob/master/src/ES.Framework/RabbitMQ/BaseEvent.cs

https://github.com/wrx362114/EasyMQService/blob/master/src/ES.Framework/RabbitMQ/EventHandler/TimedTaskHandler.cs

吴瑞祥 | 园豆:29449 (高人七级) | 2018-03-05 17:26
0

Method 1:

public class Base<T>:IInterface where T:IParamter

{

  protected Base<T>(){}

}

public class A:Base<ParamterA>{}

或者你接口有个叫初始化的函数,里面跟参数

Method 2:

参数类型直接 object[]——可以参见反射等均用此方式;

花飘水流兮 | 园豆:13560 (专家六级) | 2018-03-05 19:32
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册