List类的类型转换问题

时间:2010-06-21 12:35:24

标签: c# asp.net

这里的错误是什么?

private void LoadUsers(List<long> uids, EventUser.EventUserStatus eventUserStatus, IList<user> chkfriends)
{
    foreach (var f in chkfriends) 
    {
      long l = f.uid; <-- fails
       if (uids.Contains(l)) do it!
    }

错误1无法隐式转换类型'long?' '长'。存在显式转换(您是否错过了演员?)

6 个答案:

答案 0 :(得分:2)

f.uid大概是long? - 在这种情况下只是:

long l = f.uid.Value;

这假设uid的值不为空。如果集合中可能有null个ID,则可能是:

if(f.uid != null && uids.Contains(f.uid.Value)) {
    // do it!
}

答案 1 :(得分:0)

long l = f.uid.Value;

错误是f.uidNullable<long>,您正试图将其分配给long

答案 2 :(得分:0)

f.uid可以为空(System.Nullable<long>),所以你不能把它分配给长。

尝试:

long? l = f.uid;

或者也许:

if ( f.uid == null ) 
    throw new NullReferenceException("Uid cannot be null");
long l = f.uid.Value;

如果uid为null,则可能是错误情况,在这种情况下,抛出异常将是合适的。你可以read more about nullable types here

答案 3 :(得分:0)

您的本地变量l属于long类型,而字段或属性user.uid似乎属于Nullable<long>类型(又名long?) - 因此不允许转让。

答案 4 :(得分:0)

uid是可以为空的,所以将你的陈述改为这个,它应该有效。

long l = f.uid ?? 0;

答案 5 :(得分:0)

还有一个选择。

if (!f.uid.HasValue)   
    throw new NullReferenceException("Uid cannot be null");  
long l = f.uid.Value;