【问题标题】:how to fix operator '==' is ambiguous on operands of type ulong and long如何修复运算符 '==' 在 ulong 和 long 类型的操作数上不明确
【发布时间】:2019-08-27 17:51:57
【问题描述】:

我目前正在我的 Discord 服务器中构建一个新命令,我正在努力将 UserId 转换回我服务器中的用户昵称。

我收到错误消息运算符“==”在 ulong 和 long 类型的操作数上不明确

谁能帮我弄清楚我做错了什么

Int64 memberId = reader.GetInt64(0);
string name = Context.Guild.Users
    .Where(x => x.Id == memberId)
    .First()
    .Nickname != null 
        ? Context.Guild.Users.Where(x => x.Id = memberId).First().Nickname 
        : Context.Guild.Users.Where(x => x.Id = memberId).First().Username;
Int64 votes = reader.GetInt64(2);
GOTWVote.Add($@"{name} has received {votes} vote(s)");

【问题讨论】:

  • Where(x => x.Id = memberId) 这不会编译。
  • Where(x => x.Id = memberId) 应该是 Where(x => x.Id == memberId)。您正在使用赋值(=)运算符,需要使用比较器(==)。
  • @Grant,成功了!谢谢!

标签: c# sql discord


【解决方案1】:

.Where(x => x.Id = memberId) 中,您应该使用== 进行比较,而不是像以前那样使用=(归因)。

Int64 memberId = reader.GetInt64(0);
string name = Context.Guild.Users
    .Where(x => x.Id == memberId)
    .First()
    .Nickname != null 
        ? Context.Guild.Users.Where(x => x.Id == memberId).First().Nickname 
        : Context.Guild.Users.Where(x => x.Id == memberId).First().Username;
Int64 votes = reader.GetInt64(2);
GOTWVote.Add($@"{name} has received {votes} vote(s)");

但是你可以将这段代码重构为这个(读到 cmets):

var memberId = reader.GetInt64(0);
// search for the user just a single time!
var user = Context.Guild.Users.First(x => x.Id == memberId);

// apply the rule to define the name string
string name = @string.IsNullOrEmpty(user.Nickname) ? user.Nickname : user.Username;

var votes = reader.GetInt64(2);
GOTWVote.Add($@"{name} has received {votes} vote(s)");

【讨论】:

    【解决方案2】:

    尝试将memberId 转换为ulong(或UInt64),以便类型匹配x.Id

    var memberId = (ulong)reader.GetInt64(0);
    string name = Context.Guild.Users
        .Where(x => x.Id == memberId)
        ...
        ...
    

    此外,正如其他答案和 cmets 所建议的那样,您还有一些其他问题需要解决。 ;)

    【讨论】:

      【解决方案3】:

      第一步是通过强制转换来解决歧义运算符。接下来,重新排列查询以去除两个额外的子查询:

      Int64 memberId = reader.GetInt64(0);
      var user = Context.Guild.Users
          .Where(x => x.Id == (UInt64)memberId)
          .First();
      
      string name = 
          user.Nickname != null 
              ? user.Nickname 
              : user.Username;
      
      Int64 votes = reader.GetInt64(2);
      GOTWVote.Add($@"{name} has received {votes} vote(s)");
      

      【讨论】:

      • 一旦我将 Uint 更改为 UInt,这也有效
      猜你喜欢
      • 1970-01-01
      • 2014-05-27
      • 1970-01-01
      • 2023-02-10
      • 1970-01-01
      • 2023-04-07
      • 2012-09-21
      • 1970-01-01
      • 2022-06-11
      相关资源
      最近更新 更多