标签: system.reflection

使用System.Type调用泛型方法

我使用的是C#/ .NET 4.0和一个Protocol Buffers库(protobuf-net),它提供了以下功能.

public static class Serializer {
    public static void Serialize<T>(Stream destination, T instance);
    public static void Serialize<T>(SerializationInfo info, T instance);
    public static void Serialize<T>(XmlWriter writer, T instance);
    public static void Serialize<T>(SerializationInfo info, StreamingContext context, T instance);
    public static T Deserialize<T>(Stream source);
}
Run Code Online (Sandbox Code Playgroud)

我需要使用非泛型等价物包装其中两个调用.具体来说,我想要

void SerializeReflection(Stream destination, object instance);
object DeserializeReflection(Stream source, Type type);
Run Code Online (Sandbox Code Playgroud)

它只是Serializer在运行时调用相应的通用成员.我已经得到了DeserializeReflection使用以下代码的方法:

public static object DeserializeReflection(Stream stream, Type type)
{
    return typeof(Serializer)
        .GetMethod("Deserialize")
        .MakeGenericMethod(type)
        .Invoke(null, new object[] { stream …
Run Code Online (Sandbox Code Playgroud)

.net c# generics system.reflection

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

使用System.Reflection打印所有System.Environment信息

我们有一个小任务在控制台窗口中打印所有Environment类的变量使用reflection,但是怎么做我甚至都没有线索.如果我在这里写错了,我很抱歉,我是新来的C#.

当然我可以使用这种代码,但这不是我所要求的.

string machineName = System.Environment.MachineName;
Console.WriteLine(machineName);
Run Code Online (Sandbox Code Playgroud)

我搜索了Google这么多,这就是我找到的,但我认为这不是我需要的.我甚至不知道我需要什么.

System.Reflection.Assembly info = typeof(System.Int32).Assembly;
System.Console.WriteLine(info);
Run Code Online (Sandbox Code Playgroud)

有什么建议,线索?

c# environment-variables console-application system.reflection

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

Typelite:如何使用T4转换将可空C#类型设置为可空的Typescript类型?

我正在使用Typelite 9.5.0将我的C#类转换为Typescript接口.我想要一个可以为空的类型(例如Guid?)在Typescript中转换为可空类型.

目前我有这个C#类:

public class PersistentClassesReferences
{
public Guid? EmailMessageId { get; set; }
public Guid? FileMetaDataId { get; set; }
public Guid? IssueId { get; set; }
public Guid? ProjectId { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

但是使用Typelite将其转换为此Typescript接口:

interface IPersistentClassesReferences {
    EmailMessageId : System.IGuid;
    FileMetaDataId : System.IGuid;
    IssueId : System.IGuid;
    ProjectId : System.IGuid;
}
Run Code Online (Sandbox Code Playgroud)

但是当我想从这个接口创建一个新的typescript变量时,编译器会在我没有设置所有属性时抱怨(某些值为null).

因此,我有一个模板,可以测试可空类型,如果有的话,添加一个?

var isNullabe = Nullable.GetUnderlyingType(tsprop.ClrProperty.PropertyType) != null;
if (isNullabe)
{
    return identifier.Name + "? ";
}
Run Code Online (Sandbox Code Playgroud)

这确实有效,但现在不行了(我想在升级到Typelite 9.5.0或其他一些nugetpackage更新之后).

我收到错误消息:

 Compiling transformation: 'System.Reflection.MemberInfo' does not contain a …
Run Code Online (Sandbox Code Playgroud)

reflection t4 system.reflection typescript typelite

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

如何使用动态生成的对象作为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
查看次数

从 Assembly.ReflectionOnlyLoad 迁移到 MetadataLoadContext

我有以下代码适用于 .NET 4.8 类库,它使用Assembly.ReflectionOnlyLoad

代码:

// Retrieve the doman assembly used by the compilation
Assembly baseAssembly = typeof(MyType).Assembly;

// Retrieve the location of the assembly and the referenced assemblies used by the domain
AssemblyName[] baseAssemblyReferences = baseAssembly.GetReferencedAssemblies();
List<string> baseAssemblyLocations = baseAssemblyReferences.Select(a => Assembly.ReflectionOnlyLoad(a.FullName).Location).ToList();
baseAssemblyLocations.Add(baseAssembly.Location);

// Create Compilation Parameters
CompilerParameters compileParams = new CompilerParameters()
{
    CompilerOptions = Constants.Assembly.CompileToLibrary,
    GenerateInMemory = true
};
compileParams.ReferencedAssemblies.AddRange(baseAssemblyLocations.ToArray());

// Create Code Provider
CSharpCodeProvider provider = new CSharpCodeProvider(new Dictionary<string, string>() {
        { Constants.Assembly.CompilerVersion, Constants.Assembly.CompilerVersion4 }
    }); …
Run Code Online (Sandbox Code Playgroud)

c# system.reflection .net-6.0 metadataloadcontext

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