【发布时间】:2019-05-10 15:19:15
【问题描述】:
我有一个通用函数(object, object),其中一个参数可以是 new() 当我尝试将对象与 new() 进行比较时,它总是错误的。
public static void TestFunction<T>(object requestData, object storedData) where T : class, new()
{
if (requestData != null && storedData != null)
if (requestData?.GetType().Name != storedData?.GetType().Name)
{ throw new Exception("object types are not match"); return; }
if (requestData == null) throw new Exception("request can not be null");
```
//storedData might be new T()
// but even i am creating new objects to compare inside function - no luck
```
object o = (T)Activator.CreateInstance(typeof(T));
object o1 = (T)Activator.CreateInstance(typeof(T));
object o2 = new T();
T test = new T();
```//all return false
o.Equals(o1).Dump();
test.Equals(new T()).Dump();
o2.Equals(o).Dump();
}
我希望比较是正确的。
【问题讨论】:
-
它们是两个不同的引用,所以除非 T 是值类型,否则它们总是会比较 false。为了解决这个问题,在你的类上实现
IEquatable。然后,当您致电Equals()时,它会按照您的预期行事。 -
@HereticMonkey:那篇文章讨论了
==,这里没有用到。 -
谢谢。我找到了article中描述的解决方案: