获取.NET Core 2.0网络成本的最佳方法

5
有没有一种方法可以在 .Net Core 2.0 上找到网络成本?
以下是我在 c++ 代码中获取网络成本的方式:
hr = pNetworkCostManager->GetCost(&dwCost, NULL);
if (hr == S_OK) {
    switch (dwCost) {
    case NLM_CONNECTION_COST_UNRESTRICTED:  
    case NLM_CONNECTION_COST_FIXED:         
    case NLM_CONNECTION_COST_VARIABLE:      
    case NLM_CONNECTION_COST_OVERDATALIMIT: 
    case NLM_CONNECTION_COST_CONGESTED:    
    case NLM_CONNECTION_COST_ROAMING:     
    case NLM_CONNECTION_COST_APPROACHINGDATALIMIT:
    case NLM_CONNECTION_COST_UNKNOWN:
    }
}

.Net Core(2.0)中有一个NetworkInterfaceType(https://learn.microsoft.com/en-us/dotnet/api/system.net.networkinformation.networkinterfacetype?view=netcore-1.0)。根据NetworkInterfaceType,我可以看到它是否具有wifi、网络或移动连接,但这不会转化为成本。在.Net Core 2.0上有没有找到Network cost的方法呢?

在你的C++示例中,pNetworkCostManager是从哪里来的? - Gimly
@Gimly 它是一个 https://msdn.microsoft.com/zh-cn/library/windows/desktop/hh448257(v=vs.85).aspx 对象。 - Mark
你是在尝试确定计量使用还是无限制使用(即货币)?还是你是在尝试确定性能(速度位/秒)? - Sql Surfer
@SqlSurfer 计量版 vs 无限制版 - Mark
1个回答

3

要调用GetCost,您需要使用COM接口。如果您需要精确地进行此调用,即将NULL而不是IP地址传递到GetCost中,则必须自己定义COM接口以满足您的需求,例如:

using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

[ComImport, Guid("DCB00C01-570F-4A9B-8D69-199FDBA5723B"), ClassInterface(ClassInterfaceType.None)]
public class NetworkListManager : INetworkCostManager
{
    [MethodImpl(MethodImplOptions.InternalCall)]
    public virtual extern void GetCost(out uint pCost, [In] IntPtr pDestIPAddr);
}


[ComImport, Guid("DCB00008-570F-4A9B-8D69-199FDBA5723B"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface INetworkCostManager
{
    void GetCost(out uint pCost, [In] IntPtr pDestIPAddr);
}

然后您可以像这样获取成本信息:
new NetworkListManager().GetCost(out uint cost, IntPtr.Zero);

如果不需要传递NULLGetCost,你可以简单地添加对COM类型库“Network List Manager 1.0 Type Library”的引用,将“嵌入互操作类型”设置为false,并使用这些定义

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接