更具体地说,如果我有:
public class TempClass : TempInterface
{
int TempInterface.TempProperty
{
get;
set;
}
int TempInterface.TempProperty2
{
get;
set;
}
public int TempProperty
{
get;
set;
}
}
public interface TempInterface
{
int TempProperty
{
get;
set;
}
int TempProperty2
{
get;
set;
}
}
Run Code Online (Sandbox Code Playgroud)
如何使用反射来获取显式实现TempInterface的属性的所有propertyInfos?
谢谢.
给定类型a和类型b,我如何在运行时确定是否存在从a到b的隐式转换?
如果这没有意义,请考虑以下方法:
public PropertyInfo GetCompatibleProperty<T>(object instance, string propertyName)
{
var property = instance.GetType().GetProperty(propertyName);
bool isCompatibleProperty = !property.PropertyType.IsAssignableFrom(typeof(T));
if (!isCompatibleProperty) throw new Exception("OH NOES!!!");
return property;
}
Run Code Online (Sandbox Code Playgroud)
这是我想要工作的调用代码:
// Since string.Length is an int property, and ints are convertible
// to double, this should work, but it doesn't. :-(
var property = GetCompatibleProperty<double>("someStringHere", "Length");
Run Code Online (Sandbox Code Playgroud) 在我的插件架构中,我目前正在将插件名称(字符串),方法名称(字符串)和参数(对象数组)传递给我的插件服务,以执行指定的方法并返回结果(类型为T).
插件服务的execute方法如下所示:
public TResult Execute<TResult>(string pluginName, string operation, params object[] input) {
MethodInfo method = null;
TResult result = default(TResult);
var plugin = _plugins.Enabled().FirstOrDefault(x => x.GetType().Name.Equals(pluginName, StringComparison.InvariantCultureIgnoreCase));
if (plugin != null) {
method = plugin.GetType().GetMethods().FirstOrDefault(x => x.Name == operation);
if (method != null) {
result = (TResult)method.Invoke(plugin, input);
}
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
示例用法:
var url = AppHelper.PluginService.Execute<string>(
"ImagePlugin",
"GetImageUrl",
new object[] { image, size });
Run Code Online (Sandbox Code Playgroud)
我宁愿做的是传递匿名类型(因为我认为这更具可读性)即
var url = AppHelper.PluginService.Execute<string>(
"ImagePlugin",
"GetImageUrl",
new { image = image, targetSize = …Run Code Online (Sandbox Code Playgroud) 我编写了一个自定义序列化程序,通过反射设置对象属性.可序列化类用serializable属性标记,所有可序列化属性也被标记.例如,以下类是可序列化的:
[Serializable]
public class Foo
{
[SerializableProperty]
public string SomethingSerializable {get; set;}
public string SometthingNotSerializable {get; set;}
}
Run Code Online (Sandbox Code Playgroud)
当系列化程序被要求反序列化时SomethingSerializable,它获取属性的set方法并使用它来设置它,如下所示:
PropertyInfo propertyInfo; //the property info of the property to set
//...//
if (propertyInfo.CanWrite && propertyInfo.GetSetMethod() != null)
{
propertyInfo.GetSetMethod().Invoke(obj, new object[]{val});
}
Run Code Online (Sandbox Code Playgroud)
这工作正常,但是,如何才能使属性设置器只对序列化器可访问?如果setter是私有的:
public string SomethingSerializable {get; private set;}
Run Code Online (Sandbox Code Playgroud)
然后调用propertyInfo.GetSetMethod()在序列化器中返回null.有没有办法访问私有setter或任何其他方式,以确保只有序列化程序可以访问setter?不保证序列化程序在同一个程序集中.
通常我可以调用this.GetType(),但我无法在静态方法中访问它.我们怎么检查呢?
最近我和一位同事讨论了C++并且遗憾地说,没有办法用类字段的名字取一个字符串并用该名称提取字段; 换句话说,它缺乏反思.他给了我一个莫名其妙的表情,并询问何时有人需要做这样的事情.
除了"嘿,我现在需要立即行动"之外,我的头脑中没有一个好的答案.所以我坐下来想出了一些我用各种语言反射实际完成的事情.不幸的是,我的大多数例子来自我在Python中的Web编程,我希望这里的人会有更多的例子.这是我提出的清单:
给定一个包含
x ="Hello World!" 等行的配置文件
y = 5.0
动态设置某个config对象的字段等于该文件中的值.(这是我希望我能用C++做的,但实际上做不到.)
排序对象列表时,根据配置文件或Web请求中属性名称的任意属性进行排序.
编写使用网络协议的软件时,反射允许您根据该协议的字符串值调用方法.例如,我编写了一个IRC机器人,它将转换
!some_command arg1 arg2
为方法调用actions.some_command(arg1, arg2)并打印返回IRC通道的任何函数.
当使用Python的__getattr__函数(类似于Ruby/Smalltalk中的method_missing)时,我正在使用一个包含大量统计信息的类,例如late_total.对于每个统计数据,我希望能够添加_percent以将该统计数据作为我计算的总数的百分比(例如,stats.late_total_percent).反思使这很容易.
那么这里的任何人都可以从他们自己的编程经验中给出任何反映有用的例子吗?下一次同事问我为什么"想要做那样的事情"我想做好准备.
我的方案应该是简单的...我想要转换的类型FROM是ALWAYS "字符串".我想要转换为...可能是很多东西 - 整数,日期时间,...字符串等.
这很容易:
string valueToConvertFrom = "123";
int blah = Convert.ToInt32(valueToConvertFrom);
Run Code Online (Sandbox Code Playgroud)
但是......我不知道(直到运行时)我需要转换为的值是'Int'(或其他).我试过这个:
string valueToConvertFrom = "123";
Type convertToType = typeof(int);
object blah = Convert.ChangeType(valueToConvertFrom, convertToType);
Run Code Online (Sandbox Code Playgroud)
但这给了我以下错误:"对象必须实现IConvertible."
我不想做一个switch语句并根据类型名称调用"Convert.ToBlah"...任何建议?
我正在使用Java Reflection API,并观察到具有可变参数列表的方法变得短暂.为什么这个以及transient关键字在这种情况下意味着什么?
来自Java Glossary,transient:
Java编程语言中的关键字,指示字段不是对象的序列化形式的一部分.当对象被序列化时,其瞬态字段的值不包括在串行表示中,而其非瞬态字段的值包括在内.
然而,这个定义并未说明方法.有任何想法吗?
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
public class Dummy {
public static void main(String[] args) {
for(Method m : Dummy.class.getDeclaredMethods()){
System.out.println(m.getName() + " --> "+Modifier.toString(m.getModifiers()));
}
}
public static void foo(int... args){}
}
Run Code Online (Sandbox Code Playgroud)
输出:
main --> public static
foo --> public static transient
Run Code Online (Sandbox Code Playgroud) 我正在尝试使用propertyInfo.SetValue()方法使用反射设置对象属性值,并且我得到异常"对象与目标类型不匹配".它真的没有意义(至少对我来说!)因为我只是想在一个带有字符串替换值的对象上设置一个简单的字符串属性.这是一个代码片段 - 它包含在一个递归函数中,所以有更多的代码,但这是胆量:
PropertyInfo fieldPropertyInfo = businessObject.GetType().GetProperties().FirstOrDefault(f => f.Name.ToLower() == piecesLeft[0].ToLower());
businessObject = fieldPropertyInfo.GetValue(businessObject, null);
fieldPropertyInfo.SetValue(businessObject, replacementValue, null);
Run Code Online (Sandbox Code Playgroud)
我已经通过执行此比较验证了"businessObject"和"replacementValue"都是相同的类型,返回true:
businessObject.GetType() == replacementValue.GetType()
Run Code Online (Sandbox Code Playgroud) 虽然我明白改变价值String.Empty会是一个坏主意,但我不明白为什么我不能这样做.
为了得到我的意思,请考虑以下课程:
public class SomeContext
{
static SomeContext(){}
public static readonly string Green = "Green";
public static readonly SomeContext Instance = new SomeContext();
private SomeContext(){}
public readonly string Blue = "Blue";
public static void PrintValues()
{
Console.WriteLine(new { Green, Instance.Blue, String.Empty }.ToString());
}
}
Run Code Online (Sandbox Code Playgroud)
我有一个小的控制台应用程序,试图操纵这三个只读字段.它可以成功地将蓝色和绿色变成粉红色,但是Empty保持不变:
SomeContext.PrintValues();
/// prints out : { Green = Green, Blue = Blue, Empty = }
typeof(SomeContext).GetField("Blue").SetValue(SomeContext.Instance, "Pink");
typeof(SomeContext).GetField("Green", BindingFlags.Public | BindingFlags.Static).SetValue(null, "Pink");
typeof(String).GetField("Empty", BindingFlags.Public | BindingFlags.Static).SetValue(null, "Pink");
SomeContext.PrintValues();
/// prints out : { …Run Code Online (Sandbox Code Playgroud)