リフレクションを使用してデータ変換を実装しようとしていますコードに 1の例しています。
の GetSourceValueこの関数は、様々なタイプを比較するスイッチがありますが、私はこれらのタイプやプロパティを削除して持ちたいGetSourceValueパラメータとしてのみ単一の文字列を使用してプロパティの値を取得します。文字列でクラスとプロパティを渡し、プロパティの値を解決したいと思います。
これは可能ですか?
リフレクションを使用してデータ変換を実装しようとしていますコードに 1の例しています。
の GetSourceValueこの関数は、様々なタイプを比較するスイッチがありますが、私はこれらのタイプやプロパティを削除して持ちたいGetSourceValueパラメータとしてのみ単一の文字列を使用してプロパティの値を取得します。文字列でクラスとプロパティを渡し、プロパティの値を解決したいと思います。
これは可能ですか?
回答:
 public static object GetPropValue(object src, string propName)
 {
     return src.GetType().GetProperty(propName).GetValue(src, null);
 }もちろん、検証などを追加する必要がありますが、それはその要旨です。
src.GetType().GetProperty(propName)?.GetValue(src, null);";)。
                    GetPropertyと投げPropertyNotFoundExceptionnullの場合または何か。)
                    このようなものはどうですか:
public static Object GetPropValue(this Object obj, String name) {
    foreach (String part in name.Split('.')) {
        if (obj == null) { return null; }
        Type type = obj.GetType();
        PropertyInfo info = type.GetProperty(part);
        if (info == null) { return null; }
        obj = info.GetValue(obj, null);
    }
    return obj;
}
public static T GetPropValue<T>(this Object obj, String name) {
    Object retval = GetPropValue(obj, name);
    if (retval == null) { return default(T); }
    // throws InvalidCastException if types are incompatible
    return (T) retval;
}これにより、次のように単一の文字列を使用してプロパティに降りることができます。
DateTime now = DateTime.Now;
int min = GetPropValue<int>(now, "TimeOfDay.Minutes");
int hrs = now.GetPropValue<int>("TimeOfDay.Hours");これらのメソッドは、静的メソッドまたは拡張として使用できます。
PropertyInfo.PropertyTypeなく、最後のプロパティタイプを追跡して使用する方がきれいobj.GetType()です。
                    nameofようにC#6以降の式をnameof(TimeOfDay.Minutes)関数を呼び出してマジック文字列を削除し、これらの呼び出しにコンパイル時の安全性を追加するときに、nameパラメーターで式を  ます。
                    に追加Class:
public class Foo
{
    public object this[string propertyName]
    {
        get { return this.GetType().GetProperty(propertyName).GetValue(this, null); }
        set { this.GetType().GetProperty(propertyName).SetValue(this, value, null); }
    }
    public string Bar { get; set; }
}その後、次のように使用できます。
Foo f = new Foo();
// Set
f["Bar"] = "asdf";
// Get
string s = (string)f["Bar"];SetValueおよびGetValueメソッドはで動作しObjectます。特定のタイプで作業する必要がある場合は、結果をGetValueキャストし、それを割り当てる値をキャストする必要がありますSetValue
                    どのような使用方法についてCallByNameのMicrosoft.VisualBasic名前空間(Microsoft.VisualBasic.dll)?リフレクションを使用して、通常のオブジェクト、COMオブジェクト、さらには動的オブジェクトのプロパティ、フィールド、メソッドを取得します。
using Microsoft.VisualBasic;
using Microsoft.VisualBasic.CompilerServices;その後
Versioned.CallByName(this, "method/function/prop name", CallType.Get).ToString();jheddingsによるすばらしい回答。propertyNameがproperty1.property2 [X] .property3になるように、集約された配列またはオブジェクトのコレクションを参照できるように改善したいと思います。
    public static object GetPropertyValue(object srcobj, string propertyName)
    {
        if (srcobj == null)
            return null;
        object obj = srcobj;
        // Split property name to parts (propertyName could be hierarchical, like obj.subobj.subobj.property
        string[] propertyNameParts = propertyName.Split('.');
        foreach (string propertyNamePart in propertyNameParts)
        {
            if (obj == null)    return null;
            // propertyNamePart could contain reference to specific 
            // element (by index) inside a collection
            if (!propertyNamePart.Contains("["))
            {
                PropertyInfo pi = obj.GetType().GetProperty(propertyNamePart);
                if (pi == null) return null;
                obj = pi.GetValue(obj, null);
            }
            else
            {   // propertyNamePart is areference to specific element 
                // (by index) inside a collection
                // like AggregatedCollection[123]
                //   get collection name and element index
                int indexStart = propertyNamePart.IndexOf("[")+1;
                string collectionPropertyName = propertyNamePart.Substring(0, indexStart-1);
                int collectionElementIndex = Int32.Parse(propertyNamePart.Substring(indexStart, propertyNamePart.Length-indexStart-1));
                //   get collection object
                PropertyInfo pi = obj.GetType().GetProperty(collectionPropertyName);
                if (pi == null) return null;
                object unknownCollection = pi.GetValue(obj, null);
                //   try to process the collection as array
                if (unknownCollection.GetType().IsArray)
                {
                    object[] collectionAsArray = unknownCollection as object[];
                    obj = collectionAsArray[collectionElementIndex];
                }
                else
                {
                    //   try to process the collection as IList
                    System.Collections.IList collectionAsList = unknownCollection as System.Collections.IList;
                    if (collectionAsList != null)
                    {
                        obj = collectionAsList[collectionElementIndex];
                    }
                    else
                    {
                        // ??? Unsupported collection type
                    }
                }
            }
        }
        return obj;
    }私からのコードを使用している場合はエドS. IのGET
保護レベルが原因で「ReflectionExtensions.GetProperty(Type、string)」にアクセスできません
それはそうGetProperty()Xamarin.Formsでは使用できません。TargetFrameworkProfileですProfile7私のポータブルクラスライブラリ(.NET Frameworkの4.5、Windows 8の、ASP.NETコア1.0、Xamarin.Android、Xamarin.iOS、Xamarin.iOSクラシック)で。
今私は実用的な解決策を見つけました:
using System.Linq;
using System.Reflection;
public static object GetPropValue(object source, string propertyName)
{
    var property = source.GetType().GetRuntimeProperties().FirstOrDefault(p => string.Equals(p.Name, propertyName, StringComparison.OrdinalIgnoreCase));
    return property?.GetValue(source);
}ネストされたプロパティの説明について、DataBinder.Eval Method (Object, String)以下のように使用すると、すべてのリフレクションを回避できます。
var value = DataBinder.Eval(DateTime.Now, "TimeOfDay.Hours");もちろん、System.Webアセンブリへの参照を追加する必要がありますが、これはおそらく大したことではありません。
System.Reflection名前空間のPropertyInfoを使用します。リフレクションは、アクセスしようとするプロパティに関係なく正常にコンパイルされます。エラーは実行時に発生します。
    public static object GetObjProperty(object obj, string property)
    {
        Type t = obj.GetType();
        PropertyInfo p = t.GetProperty("Location");
        Point location = (Point)p.GetValue(obj, null);
        return location;
    }オブジェクトのLocationプロパティを取得することはうまくいきます
Label1.Text = GetObjProperty(button1, "Location").ToString();Locationを取得します:{X = 71、Y = 27}同じ方法でlocation.Xまたはlocation.Yを返すこともできます。
public static List<KeyValuePair<string, string>> GetProperties(object item) //where T : class
    {
        var result = new List<KeyValuePair<string, string>>();
        if (item != null)
        {
            var type = item.GetType();
            var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
            foreach (var pi in properties)
            {
                var selfValue = type.GetProperty(pi.Name).GetValue(item, null);
                if (selfValue != null)
                {
                    result.Add(new KeyValuePair<string, string>(pi.Name, selfValue.ToString()));
                }
                else
                {
                    result.Add(new KeyValuePair<string, string>(pi.Name, null));
                }
            }
        }
        return result;
    }これは、リスト内のすべてのプロパティとその値を取得する方法です。
type.GetProperty(pi.Name)をしているのですpiか?==が変数に対して?
                    ifしているselfValue?.ToString()場合はif、selfValue==null?null:selfValue.ToString()
                    List<KeyValuePair<は奇妙です。辞書を使用してくださいDictionary<string, string>
                    次のコードは、オブジェクトのインスタンスに含まれるすべてのプロパティ名と値の階層全体を表示するための再帰的なメソッドです。このメソッドは、GetPropertyValue()このスレッドで上記のAlexDの回答の簡略版を使用します。このディスカッションスレッドのおかげで、これを行う方法を見つけることができました。
たとえば、このメソッドを使用してWebService、次のようにメソッドを呼び出し、応答内のすべてのプロパティの展開またはダンプを表示します。
PropertyValues_byRecursion("Response", response, false);
public static object GetPropertyValue(object srcObj, string propertyName)
{
  if (srcObj == null) 
  {
    return null; 
  }
  PropertyInfo pi = srcObj.GetType().GetProperty(propertyName.Replace("[]", ""));
  if (pi == null)
  {
    return null;
  }
  return pi.GetValue(srcObj);
}
public static void PropertyValues_byRecursion(string parentPath, object parentObj, bool showNullValues)
{
  /// Processes all of the objects contained in the parent object.
  ///   If an object has a Property Value, then the value is written to the Console
  ///   Else if the object is a container, then this method is called recursively
  ///       using the current path and current object as parameters
  // Note:  If you do not want to see null values, set showNullValues = false
  foreach (PropertyInfo pi in parentObj.GetType().GetTypeInfo().GetProperties())
  {
    // Build the current object property's namespace path.  
    // Recursion extends this to be the property's full namespace path.
    string currentPath = parentPath + "." + pi.Name;
    // Get the selected property's value as an object
    object myPropertyValue = GetPropertyValue(parentObj, pi.Name);
    if (myPropertyValue == null)
    {
      // Instance of Property does not exist
      if (showNullValues)
      {
        Console.WriteLine(currentPath + " = null");
        // Note: If you are replacing these Console.Write... methods callback methods,
        //       consider passing DBNull.Value instead of null in any method object parameters.
      }
    }
    else if (myPropertyValue.GetType().IsArray)
    {
      // myPropertyValue is an object instance of an Array of business objects.
      // Initialize an array index variable so we can show NamespacePath[idx] in the results.
      int idx = 0;
      foreach (object business in (Array)myPropertyValue)
      {
        if (business == null)
        {
          // Instance of Property does not exist
          // Not sure if this is possible in this context.
          if (showNullValues)
          {
            Console.WriteLine(currentPath  + "[" + idx.ToString() + "]" + " = null");
          }
        }
        else if (business.GetType().IsArray)
        {
          // myPropertyValue[idx] is another Array!
          // Let recursion process it.
          PropertyValues_byRecursion(currentPath + "[" + idx.ToString() + "]", business, showNullValues);
        }
        else if (business.GetType().IsSealed)
        {
          // Display the Full Property Path and its Value
          Console.WriteLine(currentPath + "[" + idx.ToString() + "] = " + business.ToString());
        }
        else
        {
          // Unsealed Type Properties can contain child objects.
          // Recurse into my property value object to process its properties and child objects.
          PropertyValues_byRecursion(currentPath + "[" + idx.ToString() + "]", business, showNullValues);
        }
        idx++;
      }
    }
    else if (myPropertyValue.GetType().IsSealed)
    {
      // myPropertyValue is a simple value
      Console.WriteLine(currentPath + " = " + myPropertyValue.ToString());
    }
    else
    {
      // Unsealed Type Properties can contain child objects.
      // Recurse into my property value object to process its properties and child objects.
      PropertyValues_byRecursion(currentPath, myPropertyValue, showNullValues);
    }
  }
}public static TValue GetFieldValue<TValue>(this object instance, string name)
{
    var type = instance.GetType(); 
    var field = type.GetFields(BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance).FirstOrDefault(e => typeof(TValue).IsAssignableFrom(e.FieldType) && e.Name == name);
    return (TValue)field?.GetValue(instance);
}
public static TValue GetPropertyValue<TValue>(this object instance, string name)
{
    var type = instance.GetType();
    var field = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance).FirstOrDefault(e => typeof(TValue).IsAssignableFrom(e.PropertyType) && e.Name == name);
    return (TValue)field?.GetValue(instance);
}public class YourClass
{
    //Add below line in your class
    public object this[string propertyName] => GetType().GetProperty(propertyName)?.GetValue(this, null);
    public string SampleProperty { get; set; }
}
//And you can get value of any property like this.
var value = YourClass["SampleProperty"];以下の方法は私にとって完璧に機能します:
class MyClass {
    public string prop1 { set; get; }
    public object this[string propertyName]
    {
        get { return this.GetType().GetProperty(propertyName).GetValue(this, null); }
        set { this.GetType().GetProperty(propertyName).SetValue(this, value, null); }
    }
}プロパティ値を取得するには:
MyClass t1 = new MyClass();
...
string value = t1["prop1"].ToString();プロパティ値を設定するには:
t1["prop1"] = value;ネストされたパスを通知する文字列を必要としない、ネストされたプロパティを見つける別の方法を次に示します。単一のプロパティメソッドのEd S.の功績です。
    public static T FindNestedPropertyValue<T, N>(N model, string propName) {
        T retVal = default(T);
        bool found = false;
        PropertyInfo[] properties = typeof(N).GetProperties();
        foreach (PropertyInfo property in properties) {
            var currentProperty = property.GetValue(model, null);
            if (!found) {
                try {
                    retVal = GetPropValue<T>(currentProperty, propName);
                    found = true;
                } catch { }
            }
        }
        if (!found) {
            throw new Exception("Unable to find property: " + propName);
        }
        return retVal;
    }
        public static T GetPropValue<T>(object srcObject, string propName) {
        return (T)srcObject.GetType().GetProperty(propName).GetValue(srcObject, null);
    }Type.GetPropertyリターンnull  の代わりに呼び出すのGetValueとなるNullReferenceExceptionのは、ループ内でスローされます。
                    検査しているオブジェクトについては決して言及せず、特定のオブジェクトを参照しているオブジェクトを拒否しているので、静的オブジェクトであると想定します。
using System.Reflection;
public object GetPropValue(string prop)
{
    int splitPoint = prop.LastIndexOf('.');
    Type type = Assembly.GetEntryAssembly().GetType(prop.Substring(0, splitPoint));
    object obj = null;
    return type.GetProperty(prop.Substring(splitPoint + 1)).GetValue(obj, null);
}検査されているオブジェクトにローカル変数でマークを付けたことに注意してくださいobj。null静的を意味します。それ以外の場合は、必要な値に設定します。またGetEntryAssembly()、「実行中」のアセンブリを取得するために使用できるいくつかのメソッドの1つであることに注意してください。型のロードに苦労している場合は、それを試してみてください。
見ていHeleonix.Reflectionのライブラリを。パスでメンバーを取得/設定/呼び出すか、リフレクションよりも速いゲッター/セッター(デリゲートにコンパイルされたラムダ)を作成できます。例えば:
var success = Reflector.Get(DateTime.Now, null, "Date.Year", out int value);または、getterを1回作成し、再利用のためにキャッシュします(これはパフォーマンスが向上しますが、中間メンバーがnullの場合はNullReferenceExceptionをスローする可能性があります)。
var getter = Reflector.CreateGetter<DateTime, int>("Date.Year", typeof(DateTime));
getter(DateTime.Now);またはList<Action<object, object>>、異なるゲッターを作成する場合は、コンパイル済みデリゲートの基本型を指定するだけです(型変換はコンパイル済みラムダに追加されます)。
var getter = Reflector.CreateGetter<object, object>("Date.Year", typeof(DateTime));
getter(DateTime.Now);より短い方法....
var a = new Test { Id = 1 , Name = "A" , date = DateTime.Now};
var b = new Test { Id = 1 , Name = "AXXX", date = DateTime.Now };
var compare = string.Join("",a.GetType().GetProperties().Select(x => x.GetValue(a)).ToArray())==
              string.Join("",b.GetType().GetProperties().Select(x => x.GetValue(b)).ToArray());jheddingsとAlexDはどちらも、プロパティ文字列を解決する方法について優れた回答を書きました。私はその目的のために専用のライブラリを書いたので、私はミックスに私を投入したいと思います。
Pather.CSharpのメインクラスはResolverです。デフォルトでは、プロパティ、配列、辞書エントリを解決できます。
たとえば、次のようなオブジェクトがある場合
var o = new { Property1 = new { Property2 = "value" } };取得したいProperty2場合は、次のように実行できます。
IResolver resolver = new Resolver();
var path = "Property1.Property2";
object result = r.Resolve(o, path); 
//=> "value"これは、解決できるパスの最も基本的な例です。他に何ができるか、またはどのように拡張できるかを確認したい場合は、Githubページにアクセスしてください。
これが私の解決策です。COMオブジェクトでも動作し、COMオブジェクトからコレクション/配列項目にアクセスできます。
public static object GetPropValue(this object obj, string name)
{
    foreach (string part in name.Split('.'))
    {
        if (obj == null) { return null; }
        Type type = obj.GetType();
        if (type.Name == "__ComObject")
        {
            if (part.Contains('['))
            {
                string partWithoundIndex = part;
                int index = ParseIndexFromPropertyName(ref partWithoundIndex);
                obj = Versioned.CallByName(obj, partWithoundIndex, CallType.Get, index);
            }
            else
            {
                obj = Versioned.CallByName(obj, part, CallType.Get);
            }
        }
        else
        {
            PropertyInfo info = type.GetProperty(part);
            if (info == null) { return null; }
            obj = info.GetValue(obj, null);
        }
    }
    return obj;
}
private static int ParseIndexFromPropertyName(ref string name)
{
    int index = -1;
    int s = name.IndexOf('[') + 1;
    int e = name.IndexOf(']');
    if (e < s)
    {
        throw new ArgumentException();
    }
    string tmp = name.Substring(s, e - s);
    index = Convert.ToInt32(tmp);
    name = name.Substring(0, s - 1);
    return index;
}ここに私が他の答えに基づいて得たものがあります。エラー処理を具体的にするために少しやりすぎです。
public static T GetPropertyValue<T>(object sourceInstance, string targetPropertyName, bool throwExceptionIfNotExists = false)
{
    string errorMsg = null;
    try
    {
        if (sourceInstance == null || string.IsNullOrWhiteSpace(targetPropertyName))
        {
            errorMsg = $"Source object is null or property name is null or whitespace. '{targetPropertyName}'";
            Log.Warn(errorMsg);
            if (throwExceptionIfNotExists)
                throw new ArgumentException(errorMsg);
            else
                return default(T);
        }
        Type returnType = typeof(T);
        Type sourceType = sourceInstance.GetType();
        PropertyInfo propertyInfo = sourceType.GetProperty(targetPropertyName, returnType);
        if (propertyInfo == null)
        {
            errorMsg = $"Property name '{targetPropertyName}' of type '{returnType}' not found for source object of type '{sourceType}'";
            Log.Warn(errorMsg);
            if (throwExceptionIfNotExists)
                throw new ArgumentException(errorMsg);
            else
                return default(T);
        }
        return (T)propertyInfo.GetValue(sourceInstance, null);
    }
    catch(Exception ex)
    {
        errorMsg = $"Problem getting property name '{targetPropertyName}' from source instance.";
        Log.Error(errorMsg, ex);
        if (throwExceptionIfNotExists)
            throw;
    }
    return default(T);
}
public static T GetPropertyValue<T>(object obj, string propName) { return (T)obj.GetType().GetProperty(propName).GetValue(obj, null); }