如何实例化内部私有类PrivateType [英] How to instantiate PrivateType of inner private class
问题描述
我试图建立一个私有内部类单元测试,但是只有很少的成功:
I was trying to setup a unit test for a private inner class, but had very little success:
namespace Stats.Model
{
public class DailyStat
{
private class DailyStatKey // The one to test
{
private DateTime date;
public DateTime Date
{
get { return date; }
set { date = value.Date; }
}
public StatType Type { get; set; }
public override int GetHashCode()
{
return Date.Year * 1000000 +
Date.Month * 10000 +
Date.Day * 100 +
(int)Type;
}
public override bool Equals(object obj)
{
DailyStatKey otherKey = obj as DailyStatKey;
if (otherKey == null)
return false;
return (this.Date == otherKey.Date && this.StatType == otherKey.StatType);
}
}
}
}
我尝试这种代码:
I tried this code:
PrivateType statKeyType = new PrivateType("Stats.Model", "Stats.Model.DailyStat.DailyStatKey");
以及
as well as
PrivateType statKeyType = new PrivateType("Stats.Model", "DailyStat.DailyStatKey");
要无果。
大会名称为Stats.Model,对我的类型名称看起来是正确的,但我却只是得到一个异常:System.TypeLoadException:未能加载类型
The assembly's name is "Stats.Model", and to me the type name looks correct too, but I just get an exception: "System.TypeLoadException: Could not load type"
所以,我在做什么错了?
So what am I doing wrong ?
PrivateType,据我所知,是基于反射,而且我想这非常适用于这种情况下,你,不能有直接的私有类命名空间下
PrivateType, to the best of my knowledge, is reflection based, and I'd guess it's pretty much intended for this scenario, as you cannot have a private class directly beneath a namespace.
编辑:
加全面实施DailyStatKey的。我想考的是我的GetHashCode方法的独特性。正如你可以看到我尝试将日期+型到单个int
Added full implementation of DailyStatKey. What I want to test is the uniqueness of my GetHashCode method. As you can see I try to fit a date + type into a single int.
推荐答案
找到了解决自己:
var parentType = typeof(DailyStat);
var keyType = parentType.GetNestedType("DailyKeyStat", BindingFlags.NonPublic);
//edited to use GetNestedType instead of just NestedType
var privateKeyInstance = new PrivateObject(Activator.CreateInstance(keyType, true));
privateKeyInstance.SetProperty("Date", DateTime.Now);
privateKeyInstance.SetProperty("Type", StatType.Foo);
var hashCode = (int)privateKeyInstance.Invoke("GetHashCode", null);
这篇关于如何实例化内部私有类PrivateType的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!