How to instantiate PrivateType of inner private class

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-03 13:01:45
Steffen

Found a solution myself:

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);

You can also use PrivateType directly as well:

PrivateType statKeyType = new PrivateType("Stats.Model", "Stats.Model.DailyStat+DailyStatKey");

Nested classes have a string format that's different from their namespace (which is Stats.Model.DailyStat.DailyStatKey) so the usage isn't obvious.

Since it is private the only class that can create the instance is DailyStat itself. Unless you make it non private reflection (activator) would be your only choice if you want to create the class although that would not be a good idea as you wont be able to use it directly unless you are able to cast it to a public enough type or interface

EDIT:

Since you are trying to do this for unit testing then effectively you shouldnt test this class as it is private. You would only be able to test it through any public interface of DailyStat.

You can code a public "GetDailyStatKey" method on parent class.

public class DailyStat
{
    private class DailyStatKey // The one to test 
    {
    }
    public DailyStatKey GetDailyStatKey()
    {
        return new  DailyStatKey();
    }
}

Now you can write:

DailyStat v = new DailyStat();
var x =  v.GetDailyStatKey();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!