如何实例化内部私有类PrivateType

编程入门 行业动态 更新时间:2024-10-26 12:30:33
本文介绍了如何实例化内部私有类PrivateType的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我试图建立一个私有内部类单元测试,但是只有很少的成功:

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

本文发布于:2023-11-04 10:13:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1557650.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:实例   PrivateType

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!