开发者

Can the GetField() method of the PrivateObject class access a private const string in C# 4.0?

开发者 https://www.devze.com 2023-02-19 11:50 出处:网络
I\'m writing a unit test that accesses a file in isolated data storage. The file name is stored in a private const string within the class because I don\'t use it anywhere else in the whole applicatio

I'm writing a unit test that accesses a file in isolated data storage. The file name is stored in a private const string within the class because I don't use it anywhere else in the whole application.

However, when I run my unit test I get a "开发者_如何学编程Field not found" error when I call the GetField("fieldName") method of the PrivateObject class instance.

string historyFileName = (string)history.GetField("ISOLATED_HISTORY_FILE");


Use the overload which you can pass BindingFlags and pass BindingFlags.NonPublic | BindingFlags.Instance.

Have a look here.


UPDATE

I thought you have a field. Const does get replaced by the literal at compile-time. Change to static readonly and pass BindingFlags.NonPublic | BindingFlags.Static.

If you cannot change the source then there is no way


Use PrivateType then call the GetStaticField method to retrieve the value of a private const.


I found the problem for any one who may have the same issue. I changed the filed from private const string to private string. Apparently, reflection doesn't recognize fields marked with const. It isn't the name I gave the filed because I tried the test with ISOLATED_HISTORY_FILE and isolatedHistoryFile and it worked both ways.

0

精彩评论

暂无评论...
验证码 换一张
取 消