簡體   English   中英

如何調用我初始化為 object 的 class 方法?

[英]How to call a class method that I initialized as an object?

我初始化 class 的代碼

PropertyInfo[] props = typeof(TObj).GetProperties();
            foreach (PropertyInfo prop in props)
            {
                var sourceAttrs = prop.GetCustomAttribute<Reference>();
                if (sourceAttrs != null)
                {
                    Type entityType = sourceAttrs.ReferenceType;
                    Type openGenericType = typeof(LinkedEntityProvider<,>);
                    Type closedGenericType = openGenericType.MakeGenericType(typeof(TObj), entityType);
                    object instanceLinkedEntityProvider = Activator.CreateInstance(closedGenericType, new object[] { Database, prop });

                }
            }

我需要調用 instanceLinkedEntityProvider 的方法。 甚至有可能做到這一點嗎?

也許通過鑄造喜歡

(LinkedEntityProvider)instanceLinkedEntityProvider.MyMethod();

或通過使用dynamic關鍵字

dynamic instanceLinkedEntityProvider = Activator.CreateInstance(closedGenericType, new object[] { Database, prop });
instanceLinkedEntityProvider.MyMethod(); //throws exception if method doesn't exist at run-time

它繞過編譯時檢查。

或者通過更多的Reflection ,您可以使用 class TypeGetMethod方法解析剛剛創建的 object 中的所有方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM