【发布时间】:2012-12-29 08:55:04
【问题描述】:
这是我的代码:
public class UserPreferences
{
/// <summary>
/// The EMail signature.
/// </summary>
[UserPreferenceProperty(Category = "Email", DefaultValue = "My default value")]
public static string Signature
{
get
{
return UserPreferenceManager.GetValue();
}
set
{
UserPreferenceManager.SetValue(value);
}
}
}
public static string GetValue()
{
if (((VTXPrincipal)Thread.CurrentPrincipal).VTXIdentity.OperatorID == null)
{
throw new Exception("Missing Operator ID");
}
string value = string.Empty;
var frame = new StackFrame(1); ***** <------ problem here.....
var property = frame.GetMethod();
var propertyname = property.Name.Split('_')[1];
var type = property.DeclaringType; ***** <------ problem here.....
if (type != null)
{
var userPreference = typeof(UserPreferences).GetProperty(propertyname).GetCustomAttributes(true).FirstOrDefault() as UserPreferencePropertyAttribute;
if (userPreference != null)
{
string category = userPreference.Category;
string description = propertyname;
value = GetValue(category, description, ((VTXPrincipal)Thread.CurrentPrincipal).VTXIdentity.OperatorID);
if (value == null)
{
// always return something
return userPreference.DefaultValue;
}
}
else
{
throw new Exception("Missing User Preference");
}
}
return value;
}
在 GetValue 方法中,StackFrame 在发布模式和调试模式下的工作方式不同。
在调试模式下,我正确地将属性名称作为签名
但在发布模式下,属性名称为 GetUserPreferenceValueTest,因为这是作为客户端进行调用的测试方法。
因此,我的代码在调试模式下工作,但在发布模式下失败。
Q. How can I use StackFrame properly so it works in Debug vs. Release modes.
Q. Is there any other way to get calling property name and related information at run time?
【问题讨论】:
-
"StackFrame 信息将在 Debug 构建配置中提供最多信息。默认情况下,Debug 构建包含调试符号,而 Release 构建不包含。调试符号包含大部分文件、方法名称、行号、和用于构造 StackFrame 对象的列信息。"
-
这是否意味着..此代码在生产中会失败,因为在生产中它将被部署为发布模式???
-
你为什么还要在 Release 中依赖 StackFrame() 呢?使用不同的设计!
-
处理这样的用户偏好是繁重且过于复杂的。网上应该有很多例子:nini.sourceforge.net