开发者

typecast problem with List class

Wha开发者_Python百科t is the bug here?

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!
    }

Error 1 Cannot implicitly convert type 'long?' to 'long'. An explicit conversion exists (are you missing a cast?)


f.uid is presumably long? - in which case just:

long l = f.uid.Value;

This assumes that the value of uid isn't empty. If there might be null ids in the set, then perhaps:

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


long l = f.uid.Value;

The bug is that f.uid is Nullable<long> and you are trying to assign it to long.


f.uid is nullable long (System.Nullable<long>), so you cannot assign it to a long.

Try:

long? l = f.uid;

Or perhaps:

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

It might be an error situation if the uid is null, in that case it would be appropiate to throw an exception. You can read more about nullable types here.


Your local variable l is of type long while the field or property user.uid seems to be of type Nullable<long> (a.k.a. long?) - therefore the assignment is not allowed.


uid is nullable so change your statement to this one and it should work.

long l = f.uid ?? 0;


one more choice.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜