gpt4 book ai didi

C# ConcurrentDictionary 使用不一致的可访问性?

转载 作者:行者123 更新时间:2023-11-30 20:39:52 25 4
gpt4 key购买 nike

我正在按照教程构建聊天客户端和服务器,现在我遇到了以下错误:

Inconsistent accessibility: field type 'System.Collections.Concurrent.ConcurrentDictionary<string,ChattingServer.ConnectedClient>' is less accessible than field 'ChattingServer.ChattingService._connectedClients' c:\Users\KOEMXE\Documents\Visual Studio 2012\Projects\ChatApplication\ChattingServer\ChattingService.cs 17  62  ChattingServer

这是相关问题所在的类文件(ChattingService.cs):

using ChattingInterfaces;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace ChattingServer
{
[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple, InstanceContextMode = InstanceContextMode.Single)]
public class ChattingService : IChattingService
{
//private ConnectedClient _connectedClients;

public ConcurrentDictionary<string, ConnectedClient> _connectedClients = new ConcurrentDictionary<string, ConnectedClient>();

public int Login(string userName)
{
//is anyone else logged in with my name?
foreach (var client in _connectedClients)
{
if(client.Key.ToLower() == userName.ToLower())
{
//if yes
return 1;
}
}

var establishedUserConnection = OperationContext.Current.GetCallbackChannel<IClient>();

ConnectedClient newClient = new ConnectedClient();
newClient.connection = establishedUserConnection;
newClient.UserName = userName;



_connectedClients.TryAdd(userName, newClient);

return 0;
}


public void SendMessageToALL(string message, string userName)
{
foreach (var client in _connectedClients)
{
if (client.Key.ToLower() != userName.ToLower())
{
client.Value.connection.GetMessage(message, userName);
}
}
}
}
}

是否需要在其他地方声明 ConcurrentDictionary 对象中的类型?有什么问题?谢谢!

最佳答案

ChattingService 是公共(public)的,它的 _connectedClients 成员也是公共(public)的。但是_connectedClients的类型涉及ChattingServer.ConnectedClient,是不公开的。

假设您要从另一个项目引用您的 ChattingServer 程序集,然后编写如下代码:

using ChattingServer;
...
ConcurrentDictionary<string, ConnectedClient> dict = myChattingService._connectedClients;

ChattingService 类型及其 _connectedClients 字段的可访问性允许您访问该字段,但类型 ConnectedClient 不是公开的,因此,根据您在 ChattingServer 程序集中放置在类型和成员上的可访问性修饰符,您可以访问应隐藏其类型的字段。这就是您收到构建错误的原因:ChattingServer 程序集中类型和成员的可访问性修饰符相互矛盾。

例如,如果您将 ChattingServer.ConnectedClient 设为公开,或将 _connectedClients 设为私有(private),这将解决问题。

关于C# ConcurrentDictionary 使用不一致的可访问性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33925483/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com