GetType()永远不等于typeof(List <string>)

时间:2018-02-06 16:21:28

标签: c# linq query-string

我遇到了一个有趣的比较问题,我很难解决,我想帮助理解为什么会发生这种情况,我能做些什么来解决它&amp;最重要的是:为什么我不应该这样做呢?我应该做的事情:P

我的模型如下所示:

public class RouteUri
{
    public string Username { get; set; }
    public string Password { get; set; }
    public List<string> Destination { get; set; }
    public string Source { get; set; }
    public string Message { get; set; }
}

这是我期望解析的通常格式,但是,我需要奇怪的时间Destinationstring类型并适当地处理它。需要将此对象处理为URI,使用字段名称作为值的QueryString键。

我注意到,当我尝试针对Destination检查typeof(List<string>)字段的类型时,我似乎无法得到肯定的结果。

考虑以下测试方法:

private static string ConvertRouteUriToUrl(DataStructures.RouteUri Url)
{
    var result = (from PropertyDescriptor property in TypeDescriptor.GetProperties(Url)
                  let test = new
                  {
                      property.Name,
                      property.DisplayName,
                      EqualityTest = property.GetType() == typeof(List<string>),
                      Property = property.GetValue(Url)?.GetType().Name,
                      Type = typeof(List<string>).Name
                  }
                  let value = property.GetType() == typeof(List<string>)
                      ? string.Join(",", property.GetValue(Url))
                      : (string)property.GetValue(Url)
                  where !string.IsNullOrEmpty(value)
                  select property.Name.ToLower() + "=" + value
                  )
                  .ToList();

    return WebUtility.UrlEncode(string.Join("&", result));
}

忽略“let value =”部分&amp;专注于Linq的“let test =”块,行EqualityTest = property.GetType()?.GetType() == typeof(List<string>)将始终返回false,并且无论我在那里放置什么比较,似乎都希望保留false

显然Destination是唯一不是字符串的字段,因此所有其他字段都将类似于下面的内容分配给test

{
    Name = "Username",
    EqualityTest = false,
    Property = "String",
    Type = "List`1"
}

正如所料,但是在处理Destination时,我看到了这一点:

{
    Name = "Destination",
    EqualityTest = false,
    Property = "List`1",
    Type = "List`1"
}

为什么这是Linq匿名类型初始化问题/功能?

我已经尝试了很多这种检查的变体,但是所有这些都已经错了,包括尝试纯粹匹配字符串;所以我非常想了解这里发生了什么。

非常感谢

编辑:

为了回答我上面提出的问题,我认为发生这种情况的原因是由于我使用的比较运算符将.GetType().Name返回的值与typeof()返回的值进行比较。

通过使用==运算符,我正在执行对象引用的比较,该对象引用比较对象的实例是否相等。我本应该使用.Equals()代替,它会根据每个值进行比较。

这就是为什么尽管两个对象输出“List`1”,但它们永远不会相等。

...

这当然没有实际意义。正如评论中提到“兰德随机”一样,我应该一直使用.PropertyType

0 个答案:

没有答案
相关问题