标签: system.reflection

与MethodBase.GetCurrentMethod等效的可移植类库

那里的Portable Class Library相当于MethodBase.GetCurrentMethod?

我是PCL的新手.我只是在研究是否可以使用PCL来保存一些肯定会在Silverlight上使用的客户端代码,并且可以在其他地方使用.扫描完源代码后,我可以看到很多对MethodBase.GetCurrentMethod的调用,这些调用似乎不存在于PCL中.

**编辑**

我已经将这个样本从有问题的库中删除了.IsNullOrEmpty()使用的是String.IsNullOrWhiteSpace(String),它似乎不可用,因此该位是一个软糖.

using System;
using System.Linq;
using System.Reflection;
using System.Linq.Expressions;

namespace LinqToLdap.PCL
{
    public static class QueryableExtensions
    {
        internal static bool IsNullOrEmpty(this String str)
        {
            return string.IsNullOrEmpty(str);
        }

        public static IQueryable<TSource> FilterWith<TSource>(this IQueryable<TSource> source, string filter)
        {
            if (source == null) throw new ArgumentNullException("source");

            if (filter.IsNullOrEmpty()) throw new Exception("Filters cannot be null, empty, or white-space.");

            if (!filter.StartsWith("("))
            {
                filter = "(" + filter + ")";
            }

            return source.Provider.CreateQuery<TSource>(
                Expression.Call(
                    null,
                    ((MethodInfo)MethodBase.GetCurrentMethod())
                        .MakeGenericMethod(new[] { typeof(TSource) }),
                    new[] …
Run Code Online (Sandbox Code Playgroud)

.net system.reflection portable-class-library

6
推荐指数
1
解决办法
961
查看次数

Assembly.LoadFile中的OutOfMemoryException

我对这个很难过.有时候,当我打电话Reflection.Assembly.LoadFile("path to my dll")时会抛出一个OutOfMemoryException.

StackTrace只显示:

at System.Reflection.RuntimeAssembly.nLoadFile(String path, Evidence evidence)
at System.Reflection.Assembly.LoadFile(String path)
Run Code Online (Sandbox Code Playgroud)

并且没有InnerException检查更详细的异常信息.

但是,似乎只通过COM.

让我解释:

我的应用程序可以作为常规旧的exe启动,或通过COM接口通过Excel启动(CreateObject("blahblahblah"))

在初始化我的一个GUI类时,它将静态加载我的所有引擎DLL(我的应用程序有一个引擎和一个GUI)

总共有6个引擎DLL - 静态加载的汇编代码在VB.NET中,看起来有点像这样:

Private Shared dllPath As String = System.IO.Path.GetDirectoryName(Reflection.Assembly.GetExecutingAssembly().Location) & System.IO.Path.DirectorySeparatorChar)
Private Shared ReadOnly engineDLL1 As Reflection.Assembly = Reflection.Assembly.LoadFile(dllPath + "engineDLL1_name.dll")
...
Private Shared ReadOnly engineDLL6 As Reflection.Assembly = Reflection.Assembly.LoadFile(dllPath + "engineDLL6_name.dll")
Run Code Online (Sandbox Code Playgroud)

我试图加载的引擎DLL是混合程序集(包含本机和托管C++) - 不确定是否重要.

无论如何,使用procexp,我注意到以标准方式打开我的应用程序,所有这些静态加载的DLL都加载正常.但是,如果我通过COM(通过Excel CreateObject("ProgID of the class with the code above"))初始化此类,它将抛出OutOfMemoryException引擎DLLL4.

如果有人可以提供任何见解,那将非常感谢!!

vb.net com c++-cli out-of-memory system.reflection

6
推荐指数
0
解决办法
470
查看次数

如何在不使用C#中的反射的情况下从该方法中获取方法名称

我想从内部获取方法名称.这可以使用reflection如下所示完成.但是,我想在不使用的情况下得到它reflection

System.Reflection.MethodBase.GetCurrentMethod().Name 
Run Code Online (Sandbox Code Playgroud)

示例代码

public void myMethod()
{
    string methodName =  // I want to get "myMethod" to here without using reflection. 
}
Run Code Online (Sandbox Code Playgroud)

c# methods system.reflection

6
推荐指数
2
解决办法
3357
查看次数

在用户定义的程序集下获取所有类型

我试图获取在特定用户定义的命名空间下定义的所有类型

Assembly.GetEntryAssembly().GetTypes().Where(t => t.Namespace == "namespace")


    <>c__DisplayClass3_0    
    <>c__DisplayClass4_0    
    <>c__DisplayClass6_0    
    <>c__DisplayClass2_0    
    <>c__DisplayClass2_1    
    <>c__DisplayClass2_2    
    <>c__DisplayClass2_3    
    <>c__DisplayClass2_4    
    <>c__DisplayClass2_5    
    <>c__DisplayClass2_6    
    <>c__DisplayClass2_7    
    <>c__DisplayClass2_8
Run Code Online (Sandbox Code Playgroud)

我的问题为什么我得到这些额外的类型没有在该命名空间下定义?

如何选择用户定义类型的类型?

有人解释了这些是什么以及如何在用户定义的命名空间中定义它们.

c# reflection system.reflection .net-core

6
推荐指数
1
解决办法
768
查看次数

如何使用动态生成的对象作为CodeEffects生成器的数据源

我们正在使用这个组件www.codeeffects.com,它允许我们根据对象属性创建业务规则。

视图的html是这样的:

@{
    ViewBag.Title = "Post Example";

    Html.CodeEffects().Styles()
        .SetTheme(ThemeType.Gray)
        .Render();
}
@using (Html.BeginForm("Evaluate", "Post", FormMethod.Post))
{
    <div class="area">
        <h1 class="title">Post Example</h1>
        <div style="margin-top:10px;">
            <span>Info:</span>
            <span style="color:Red;">@ViewBag.Message</span>
        </div>
        <div style="margin-top:10px;">
            @{
    Html.CodeEffects().RuleEditor()
        .Id("ruleEditor")
        .SaveAction("Save", "Post")
        .DeleteAction("Delete", "Post")
        .LoadAction("Load", "Post")
        .Mode(RuleType.Execution)
        .ContextMenuRules(ViewBag.ContextMenuRules)
        .ToolBarRules(ViewBag.ToolBarRules)
        .Rule(ViewBag.Rule)
        .Render();
            }
        </div>
    </div>
    <div class="area">
        <h1 class="title" style="margin-top:20px;">Rule Test Form</h1>
        @{
    Html.RenderPartial("_PatientForm");
        }
    </div>
}
@{
    Html.CodeEffects().Scripts().Render();
}
Run Code Online (Sandbox Code Playgroud)

控制器中的索引操作如下:

 [HttpGet]
        public ActionResult Index()
        {
            ViewBag.Rule = RuleModel.Create(typeof(Patient));
            return View();
        }
Run Code Online (Sandbox Code Playgroud)

Patient 类是这样的:

// External methods …
Run Code Online (Sandbox Code Playgroud)

c# asp.net reflection asp.net-mvc system.reflection

5
推荐指数
1
解决办法
929
查看次数

MethodInfo.GetCustomAttribute 上的 FileNotFoundException

我的目标是显示有关上传的 dll 中某些类的方法的信息。加载程序集、找到所需的类及其方法已经成功完成。现在我试图显示一个方法是否被声明为“异步”。

我发现一个线程告诉我如何做到这一点:How can I Tell if a C# method is async/await via Reflection?

不管怎样,在测试时,当我打电话时

(AsyncStateMachineAttribute)methodInfo.GetCustomAttribute(typeof(AsyncStateMachineAttribute))

我收到 System.IO.FileNotFoundException -“无法加载文件或程序集“{程序集标识符}”或其依赖项之一。系统找不到指定的文件。”。

我在一个未答复的线程中发现了此异常,但它对我没有帮助:How to Prevent MemberInfo.IsDefined from throwing FileNotFoundException on irrelevant attribute?

我知道我正在查看的方法有一个我的代码不知道的属性。我不想加载该引用,因为它只是一个测试用例,在相同的情况下可以找到许多其他不同的属性。

因此,我需要回答以下两个问题之一:

  1. 有没有办法获取属性“AsyncStateMachineAttribute”(如果存在),并忽略其他属性上的错误?

  2. 是否有另一种方法来检查方法(来自 MethodInfo)是否是异步的?

提前致谢!:)

.net c# reflection asynchronous system.reflection

5
推荐指数
0
解决办法
574
查看次数

如何获取实例变量的最顶层类型?

假设我有一个被声明为给定基类的实例变量。我想找到该对象实际上是什么原始的、最上面的类型,而不是基类。我该怎么做呢?

我有一个类似于 PostSharp 的验证属性,因此反射命中是在编译时发生的,因此由于该CompileTimeValidation方法而没有实际意义。我只是不知道该怎么做。进行IsSubclassOf扫描没有帮助,因为我会得到多个误报。

为了提供上下文,我有一个基本Entity类型。我从这个类型派生出所有类型的定义Entity。我Entity使用策略属性来装饰这些类型,包括基本类型。PostSharp 方面在编译时验证某些策略约束。我希望能够仅使用Entity方面验证来装饰基类型,以便Entity验证其所有派生类型。我可以看到验证已经发生。但是,它被作为 anEntity和 not处理DerivedEntity。为了评估 的策略DerviedEntity,我需要专门装饰该类。如果可能的话我想不这样做,而只是装饰Entity

本质上,我想将验证集中在基类上,因为所有派生类的验证架构都是相同的。但是,派生类中的值可能会更改,我需要进行一些边界检查。

编辑:让我们添加一些代码。

[EnforceMaxLifetimePolicy]
[LifetimePolicy]
public class Entity<T>
{
    public string Key { get; set; }
    public T Object { get; set; }

    public TimeSpan EntityLifetime
    {
        get
        {
            var lifetimePolicy =
                Attribute.GetCustomAttribute(GetType(), typeof(LifetimePolicyAttribute)) as LifetimePolicyAttribute;

            return new TimeSpan(lifetimePolicy.Hours, lifetimePolicy.Minutes, 0);
        }
    }
}

[Serializable]
[AttributeUsage(AttributeTargets.Class)]
internal class LifetimePolicyAttribute : …
Run Code Online (Sandbox Code Playgroud)

c# validation postsharp system.reflection

5
推荐指数
1
解决办法
1071
查看次数

如何使用 params 获取 Ctor 的 ConstructorInfo

我正在尝试编写接收参数列表并获取匹配 Ctor 的 ConstructorInfo 的代码。

方法签名是ConstructorInfo GetConstructorInfo(Type type, object[] args).

我创建了一个类来使用:

public class ClassWithParamsInCtor
{
    public ClassWithParamsInCtor(params int[] parameters)
    {

    }
}
Run Code Online (Sandbox Code Playgroud)

使用该类Activator我可以创建该对象的实例:

ClassWithParamsInCtor myclass = Activator.CreateInstance(typeof(ClassWithParamsInCtor), new object[] { 1,2 }) as ClassWithParamsInCtor; \\returns a valid instance of the class;
Run Code Online (Sandbox Code Playgroud)

但是当我尝试获取 ConstructorInfo 时出现问题,以下返回 null:

ConstructorInfo ctorInfo = typeof(ClassWithParamsInCtor).GetConstructor(new Type[] { typeof(int), typeof(int) }); \\returns null
Run Code Online (Sandbox Code Playgroud)

在这种情况下如何获取ConstructorInfo?

c# reflection constructor system.reflection system.type

5
推荐指数
2
解决办法
3113
查看次数

为什么通过反射更改静态只读字段后,该只读字段的输出是旧的?

为什么只读变量“someValue”(但我们仍然可以通过反射更改其值)输出为“10”,尽管它实际上确实更改为 55?

static class Program
{
    static readonly int someValue = 10;

    static void Main(string[] args)
    {
        Console.WriteLine(someValue); // 10

        typeof(Program)
             .GetField("someValue", BindingFlags.Static | BindingFlags.NonPublic)
             .SetValue(null, 55); // change readonly field via reflection to 55

        Console.WriteLine(someValue); // output in console 10, 
                                      // but in visual studio debugger it shows 55

        Console.ReadKey();
    }
}
Run Code Online (Sandbox Code Playgroud)

.net c# jit inlining system.reflection

5
推荐指数
1
解决办法
763
查看次数

在实现具有默认方法实现的接口的类上使用“GetMethod”返回 null

我有几个接口(IMapFromIMapTo),可以让我简化AutoMapper配置。每个接口都有MapToMapFrom方法的默认实现。我有一个单独的MappingProfile类,它使用反射来查找所有实现类,并调用它们的映射创建。

上述类看起来像这样:

public interface IMapFrom<T>
{
    void MapFrom(Profile profile) => profile.CreateMap(typeof(T), GetType());
}

public interface IMapTo<T>
{
    void MapTo(Profile profile) => profile.CreateMap(GetType(), typeof(T));
}

public class MappingProfile : Profile
{
    public MappingProfile()
    {
        ApplyMappingsFromAssembly(Assembly.GetExecutingAssembly());
    }

    private void ApplyMappingsFromAssembly(Assembly assembly)
    {
        var types = assembly.GetExportedTypes()
            .Where(t => t.GetInterfaces().Any(i =>
                i.IsGenericType && (i.GetGenericTypeDefinition() == typeof(IMapFrom<>) || 
                                    i.GetGenericTypeDefinition() == typeof(IMapTo<>))))
            .ToList();

        foreach (var type in types)
        {
            var instance = Activator.CreateInstance(type); …
Run Code Online (Sandbox Code Playgroud)

c# reflection system.reflection c#-8.0 default-interface-member

5
推荐指数
1
解决办法
906
查看次数