简体   繁体   English

在C#中继承NetworkInterface

[英]Inheriting NetworkInterface in C#

I have searched the web for examples of inheriting System.Net.NetworkInformation.NetworkInterface but I cannot see any elegant solutions to this. 我在网上搜索了继承System.Net.NetworkInformation.NetworkInterface的示例,但是我看不到任何优雅的解决方案。 It appears that the static method NetworkInterface.GetAllNetworkInterfaces() returns an internal implementation called SystemNetworkInterface . 似乎静态方法NetworkInterface.GetAllNetworkInterfaces()返回一个称为SystemNetworkInterface的内部实现。

Basically I want to inherit this into a class called ManagedNetworkInterface and add some additional functionality to it. 基本上,我想将其继承到一个称为ManagedNetworkInterface的类中,并为其添加一些其他功能。 Can anyone think of an elegant solution of how to do this? 谁能想到一个优雅的解决方案? I have tried, but every time, something stops me dead in my tracks! 我已经尝试过了,但是每次都让我停滞不前!

EDIT 1: 编辑1:

Is it acceptable to provide the implementation by casting the implementation back to NetworkInterface and then to ManagedNetworkInterface ? 通过将实现转换回NetworkInterface然后再转换为ManagedNetworkInterface来提供实现是否可以接受?

...this example seems messy! ...这个例子看起来很乱!

ManagedNetworkInterface mni = (ManagedNetworkInterface)(NetworkInterface)NetworkInterface.GetAllNetworkInterfaces()[0];

EDIT 2: 编辑2:

I have also thought of using a composition-like model... 我还考虑过使用类似合成的模型...

public class ManagedNetworkInterface : NetworkInterface
{
    private NetworkInterface ni;

    public override string Description
    {
        get { return ni.Description; }
    }

    //ect...
}

Is this a good or bad idea? 这是一个好主意还是坏主意?

I would write an extension method for NetworkInterface 我会为NetworkInterface编写扩展方法

public static class MyExtensions
{
    public static void MyMethod(this NetworkInterface ni)
    {
          //Some Code
    }
}

and use as ni.MyMethod() 并用作ni.MyMethod()

Issue resolved. 问题解决了。 I have used composition to inherit and implement abstract class NetworkInterface 我已经使用组合来继承和实现抽象类NetworkInterface

Code

public class ManagedNetworkInterface : NetworkInterface
{
    private NetworkInterface ni;

    public override string Description
    {
        get { return ni.Description; }
    }

    //ect...
}

The new class now includes several mechanisms for creating instances of ManagedNetworkInterface using things like IP Address, Physical Address, ID, Name etc. 现在,新类包括几种使用IP地址,物理地址,ID,名称等创建ManagedNetworkInterface实例的机制。

class NetworkAdapter : NetworkInterface
{
    private NetworkInterface ni;

    public override string Description => _nic.Description;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM