标签: system.reflection

反射 GetValue null 属性

此方法比较同一类的两个对象:

foreach (var field in fields.Where(field => !objTarget
        .GetType().GetProperty(field).GetValue(objTarget, null)
        .Equals(obj.GetType().GetProperty(field).GetValue(obj, null))))
Run Code Online (Sandbox Code Playgroud)

如果这两个属性都有它正常工作的值,但有时我在这两个对象之一中有一个空属性,我该如何处理?

编辑:如果我比较两个对象,即:

var a = new Test();
var b = new Test();
a.Property1 = "1";
b.Property1 = null;
Run Code Online (Sandbox Code Playgroud)

我得到空引用异常:

ConsoleApplication1.exe 中发生类型为“System.NullReferenceException”的未处理异常

.net c# null system.reflection

2
推荐指数
1
解决办法
1万
查看次数

获取类属性的属性

我想获得类的属性的属性.

我现在拥有的:

foreach (var v in test.GetType().GetProperties())
{
    foreach (var p in v.GetType().GetProperties())
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

第一个foreach循环工作正常,并获取类变量的属性test.然而,在第二循环中,我得到的输出,例如MemberType,ReflectedType,Module等不是实际属性.

我的目标是获取类属性的属性,然后编辑它们的值(使用另一个函数截断它们).

谢谢.

c# reflection system.reflection

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

检查实体的属性是否通过反射和 EF Core 标记为 IsRequired()

问题

如果我有某个实体的一组属性并且我正在遍历它们,有没有办法检查我在每个循环中迭代的反射类型属性是否配置.IsRequired()为其对应的实体?

例子

这个问题必须特别针对string属性,就像在大多数值类型中一样,如果 db 属性允许null值,那么它会被 EF Core 的 Scaffolding 操作映射为可空类型。

EG:可以为空的 int 被映射为int?,而不可为空的 int被映射为int

如果我遍历该映射实体的属性,以检查我现在正在迭代的该属性是否为可空属性,我只需要检查是否myproperty.PropertyType == typeof(int?)但是...如果是string类型呢?

有没有办法检查它是否被标记为.IsRequired()属性?

到目前为止我的代码

在我的代码中,我有以下函数,它应该作为参数接收:

  • objectInstance:从我必须更新的实体派生的代理,我(必须)之前找到
  • values:包含属性名称和我必须更新的属性的新值的字典。它可以填充所有属性,或者只填充其中的一些。
  • properties:我之前通过反射找到的类的属性数组

这个函数应该遍历属性数组,并且对于每个属性,如果新值包含在字典中,则在类的实例上设置其新值。

private static bool SetValues(Object objectInstance, Dictionary<string, object> values, PropertyInfo[] properties)
{
    bool edited = false;
    foreach (var item in values)
    {
        var temp = properties.Where(w => w.Name.ToLower() == item.Key.ToLower()).FirstOrDefault();
        if (temp != null)
        {
            edited …
Run Code Online (Sandbox Code Playgroud)

c# system.reflection entity-framework-core

2
推荐指数
1
解决办法
1443
查看次数

抛出 NullReferenceException 但对象通过了 null 检查,这怎么可能?

我正在使用该答案中的AddEventHandler方法,但是当在具有值类型参数的EventHandler上执行此操作时,会发生:

using System.Reflection;

public class Program
{
    public static event EventHandler<bool> MyEvent;

    public static void Main()
    {
        EventInfo eventInfo = typeof(Program).GetEvent(nameof(MyEvent));
        AddEventHandler(eventInfo, null, (s, e) => {
            if (e == null) return; // either if condition or null conditional operator
            Console.WriteLine(e?.ToString());
        });
        MyEvent(null, true);
    }

    public static void AddEventHandler(EventInfo eventInfo, object client, EventHandler handler)
    {
        object eventInfoHandler = eventInfo.EventHandlerType
            .GetConstructor(new[] { typeof(object), typeof(IntPtr) })
            .Invoke(new[] { handler.Target, handler.Method.MethodHandle.GetFunctionPointer() });

        eventInfo.AddEventHandler(client, (Delegate)eventInfoHandler);
    }
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

有什么解释吗?

c# delegates system.reflection eventhandler .net-6.0

2
推荐指数
1
解决办法
251
查看次数

创建表单实例时出现反射错误

我一直在试验一个将扫描程序集的应用程序,检查任何表单类,然后查看它们的成员.

我用来查询程序集的代码是:

 Assembly testAssembly = Assembly.LoadFile(assemblyPath);

 Type[]  types = testAssembly.GetTypes();
 textBox1.Text = "";

 foreach (Type type in types)
 {
     if (type.Name.StartsWith("Form"))
     {
         textBox1.Text += type.Name + Environment.NewLine;

         Type formType = testAssembly.GetType();
         Object form = Activator.CreateInstance(formType);       
      }
 }
Run Code Online (Sandbox Code Playgroud)

我用它来查询标准表单:

 using System;
 using System.ComponentModel;
 using System.Windows.Forms;

 namespace TestForm
 {
     public partial class Form1 : Form
     {
         public Form1()
         {
            InitializeComponent();
         }
     }
 }
Run Code Online (Sandbox Code Playgroud)

我的问题是,当代码尝试时,Activator.CreateInstance(formType)我得到一个异常说明:"No parameterless constructor defined for this object." 我也可以通过检查formType看到'DeclaringMethod:'formType.DeclaringMethod'引发类型'System.InvalidOperationException'的异常

我不明白错误信息,因为表单有一个标准的构造函数,我错过了一些非常明显的东西吗?

编辑:type.Name显示代码尝试实例化的类型Form1.

c# reflection system.reflection

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

Reflection从所有其他派生类中排除基类的所有属性和特定属性

我有以下基础,中间和派生类::

public class Base
{
    [DataMemberAttribute()]
    public int ValueBase { get; set; }

    [IgnoreForAllAttribute("Param1", "Param2")]
    public int IgnoreBase { get; set; }
}

public class Middle : Base
{
    [DataMemberAttribute()]
    public int ValueMiddle { get; set; }

    [IgnoreForAllAttribute("Param1", "Param2")]
    public int IgnoreMiddle { get; set; }
}

public class MostDerived : Middle
{
    [DataMemberAttribute()]
    public int ValueMostDerived { get; set; }

    [IgnoreForAllAttribute("Param1", "Param2")]
    public int IgnoreMostDerived { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我需要一个给定类型的函数,我需要为层次结构中除基础之外的所有类返回DataMemberAttribute属性.

此外,应该忽略图中所有类的所有IgnoreForAllAttribute属性.

var derivedObject = new MostDerived();
var attributes …
Run Code Online (Sandbox Code Playgroud)

.net c# system.reflection

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

这个对象能够告诉它有多少属性不是null/whitespace/empty有什么问题?

我试图弄清楚为什么以下代码抛出StackOverflowException(我终于在SO中发布了StackoverflowException!).

调试似乎指出p.GetValue(this)正在生成进一步的调用.

究竟是什么触发了无限的调用链?是因为p.GetValue(this)最终返回当前对象的一个​​实例,因此就像构造一个新实例一样(并且在其构造中构造自身的每个对象都会导致Stackoverflow异常)?

我对以下代码的意图是让一个对象能够告诉它有多少属性具有null/space/empty值.

public class A
{
    public string S1 { get; set; }
    public string S2 { get; set; }

    public int NonInitializedFields
    {
        get
        {
            int nonNullFields = 0;

            var properties = this.GetType().GetProperties();
            foreach (var p in properties)
            {
                var value = p.GetValue(this);
                if (value == null || string.IsNullOrWhiteSpace(value.ToString()))
                    nonNullFields++;
            }

            return nonNullFields;
        }
    }
}

//the following throws a StackOverflowException (the construction line itself)
A a1 = new A1{ S1 = "aaa"};
Console.WriteLine(a1.NonInitializedFields);
Run Code Online (Sandbox Code Playgroud)

PS我的想法最初只涉及简单的字符串属性,没有别的,所以这种方法与其他类型可能出现的问题无关紧要.

c# constructor system.reflection

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

仅通过.net反射获取受保护的成员

这将返回所有非公共实例属性:

var instanceNonPublic = currentType.GetProperties (BindingFlags.Instance |
                                                   BindingFlags.NonPublic);
Run Code Online (Sandbox Code Playgroud)

但有没有办法确定哪个访问修饰符适用于每个属性?private,internal还是protected

.net c# system.reflection

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

在c#中调用方法时如何执行属性

我有一个方法.

[AppAuthorize]
public ActionResult StolenCar(object claimContext)
{
    return View("StolenCar");
}
Run Code Online (Sandbox Code Playgroud)

我的属性是这样的代码.

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class AppAuthorize : Vairs.Presentation.AppAuthorizationAttribute
{
    public bool ConditionalAuthentication
    {
        get;
        set;
    }


    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        bool requireAuthentication = true;

        if (ConditionalAuthentication)
        {

        }

        if (requireAuthentication)
        {
            var appContext = SecurityContext.Current as SitecoreSecurityContext;

            if (appContext != null)
            {
                appContext.LoginPage =  ConfigurationManager.AppSettings[SecurityPaths.Login];
                appContext.LogoffPage = ConfigurationManager.AppSettings[SecurityPaths.Logout];
            }

            if ((appContext != null) && this.RedirectToLogin && !string.IsNullOrEmpty(appContext.LoginPage))
            {
                appContext.RedirectToLogin = true; …
Run Code Online (Sandbox Code Playgroud)

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

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

C#检查PropertyInfo的类型是否是原始的

是否可以检查存储的类型是否PropertyInfo是原始的?

例如,我想这样做:

 // from and to are both objects declared in the parameters.
 Type fType = from.GetType();
 Type tType = to.GetType();

 PropertyInfo[] fmpi = fType.GetProperties();
 PropertyInfo[] tmpi = tType.GetProperties();

 foreach(var pi in  tmpi)
 {
     if (pi.CanWrite)
     {
         var fpi = fmpi.SingleOrDefault(item => item.Name.ToLower() == pi.Name.ToLower());

         if (pi.GetType().IsPrimitive || pi.GetType() == typeof(string))
         {
             pi.SetValue(to, fpi.GetValue(from, null));
         }
     }
 }
Run Code Online (Sandbox Code Playgroud)

每当我执行此代码时,它都不会通过ifstatemenet.主要原因是每当我这样做pi.GetType()时都说它是一个PropertyInfo.这很明显,因为它被声明为PropertyInfo.但我希望你明白这个主意.

我还发现它pi.PropertyType.Name包含了属性的实际类型的名称.无论如何我可以IsPrimitive在这家酒店执行吗?如果没有,是否有任何工作让我这样做?

我检查了如何测试Type是原始的但是在这种情况下用户正在使用直接类型而我正在使用PropertyInfo.

c# system.reflection

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