Tag: reflection

C#:获取列表中所有项的任意属性的最大值和最小值

我有一个专门的列表,其中包含IThing类型的IThing : public class ThingList : IList {…} public interface IThing { Decimal Weight { get; set; } Decimal Velocity { get; set; } Decimal Distance { get; set; } Decimal Age { get; set; } Decimal AnotherValue { get; set; } […even more properties and methods…] } 有时我需要知道列表中所有内容的某个属性的最大值或最小值。 因为“告诉不要问”我们让列表弄明白: public class ThingList : IList […]

如何为给定的Type创建实例?

有了generics,你可以 var object = default(T); 但是当你拥有的只是一个Type实例时,我只能这样做 constructor = type.GetConstructor(Type.EmptyTypes); var parameters = new object[0]; var obj = constructor.Invoke(parameters); 甚至 var obj = type.GetConstructor(Type.EmptyTypes).Invoke(new object[0]); 是不是有更短的方式,如generics版本?

如何将.exe加载为.NET程序集?

我可以使用吗?: Assembly.LoadFile 不确定这是否是这样做的? 但是当我尝试这种方法时,它会抛出一个Could not load file or assembly “CustomControlLib”或其依赖项之一。 该系统找不到指定的文件。 有任何想法吗?

修剪所有字符串属性

我需要在我的对象中修剪一些字符串属性,但我不想去所有对象和属性,并且在set属性中做Trim方法(有很多对象,300+和很多字符串属性) 。 一个提示:我的所有对象都有一个名为CoreTransaction的超类,所以我可以使用它(带某种reflection)来更容易地做这件事。 那可能吗? 谢谢。

动态方法的实际例子?

我想学习动态方法及其使用c#的实际例子。 动态方法和reflection之间有什么关系吗? 请帮我。

如何将字符串值转换为对象属性名称

这是我第一次在C#/ .NET中做这样的事情,并且有点让我想起使用eval()函数或动态编写脚本并生成HTML在JavaScript中可以轻松完成的事情。 我有一个从用户输入中获取的字符串,比如string input = “foo” 。 现在我想使用值”foo”作为我拥有的对象的属性名称,例如以这样的方式cover : string input = “foo”; //magic to convert string value to be used //as a object property name goes here maybe… var success = cover.foo; C#中有没有办法可以做这样的事情? 可能使用reflection? 我已经尝试但是我总是带着一个并没有真正解决问题的对象返回。

获得依赖程序集?

有没有办法让所有程序集依赖于给定的程序集? 伪: Assembly a = GetAssembly(); var dependants = a.GetDependants();

转换为C#中的reflection类型

请考虑以下代码: object objFoo = MakeFoo(); // object MakeFoo(){return new Foo();} MethodInfo methodInfo = typeof(Program).GetMethod(“Baz”); // Foo Baz(){return foo;} Type typeFoo = methodInfo.ReturnType; var result = (typeFoo)objFoo; 我是否需要使用typeFoo做一些魔法来获得结果?

如何在运行时向方法添加属性?

我们使用Microsoft.Practices.CompositeUI.EventBroker来处理我们的应用程序中的事件订阅和发布。 可行的方法是向事件添加属性,指定主题名称,如下所示: [EventPublication(“example”, PublicationScope.Global)] public event EventHandler Example; 然后你用你的处理程序添加另一个属性,使用相同的主题名称,如下所示: [EventSubscription(“example”, ThreadOption.Publisher)] public void OnExample(object sender, EventArgs e) { … } 然后将对象传递给EventInspector,它匹配所有内容。 我们需要对此进行调试,因此我们尝试创建一个订阅所有事件的调试类。 我可以获得所有主题名称的列表……但仅限于运行时。 因此,在将调试对象传递给EventInspector之前,我需要能够在运行时向方法添加属性。 如何在运行时向方法添加属性?

使用reflection获取通用IDictionary的值

我有一个实现IDictionary的实例,我在编译时不知道T和K,并希望从中获取所有元素。 我不想出于某种原因使用IEnumerable ,这将是IDictionary实现的唯一非generics接口。 我到目前为止的代码: // getting types Type iDictType = instance.GetType().GetInterface(“IDictionary`2”); Type keyType = iDictType.GetGenericArguments()[0]; Type valueType = iDictType.GetGenericArguments()[1]; // getting the keys IEnumerable keys = (IEnumerable)dictType.GetProperty(“Keys”) .GetValue(instance, null); foreach (object key in keys) { // ==> this does not work: calling the [] operator object value = dictType.GetProperty(“Item”) .GetValue(instance, new object[] {key } ); […]