小编mbi*_*mbi的帖子

如何使用Reflection在IEnumerable <T>上调用System.Linq.Enumerable.Count <>?

我有一堆IEnumerable集合,确切的数量和类型经常更改(由于自动代码生成).

它看起来像这样:

public class MyCollections {
    public System.Collections.Generic.IEnumerable<SomeType> SomeTypeCollection;
    public System.Collections.Generic.IEnumerable<OtherType> OtherTypeCollection;
    ...
Run Code Online (Sandbox Code Playgroud)

在运行时,我想确定每个Type和它的计数,而不必在每次代码生成后重写代码.所以我正在寻找使用反射的通用方法.我正在寻找的结果是这样的:

MyType: 23
OtherType: 42
Run Code Online (Sandbox Code Playgroud)

我的问题是我无法想象如何正确调用Count方法.这是我到目前为止:

        // Handle to the Count method of System.Linq.Enumerable
        MethodInfo countMethodInfo = typeof(System.Linq.Enumerable).GetMethod("Count", new Type[] { typeof(IEnumerable<>) });

        PropertyInfo[] properties = typeof(MyCollections).GetProperties();
        foreach (PropertyInfo property in properties)
        {
            Type propertyType = property.PropertyType;
            if (propertyType.IsGenericType)
            {
                Type genericType = propertyType.GetGenericTypeDefinition();
                if (genericType == typeof(IEnumerable<>))
                {
                    // access the collection property
                    object collection = property.GetValue(someInstanceOfMyCollections, null);

                    // access the type of the generic collection …
Run Code Online (Sandbox Code Playgroud)

c# generics reflection collections ienumerable

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

发布 WKNavigationAction 子类在 iOS 15 上崩溃

对于单元测试,我将WKNavigationAction. 这是一种常见的做法,也可以在互联网和大型 SDK 中找到。

在 iOS 15 上,释放它的实例会导致 WebKit 内部崩溃。

堆栈跟踪:

Thread 1 Queue : com.apple.main-thread (serial)
#0  0x0000000130d8b702 in WTF::RunLoop::dispatch(WTF::Function<void ()>&&) ()
#1  0x0000000134ed41e4 in WebCoreObjCScheduleDeallocateOnMainRunLoop(objc_class*, objc_object*) ()
#2  0x000000011290711d in -[WKNavigationAction dealloc] ()
#3  0x000000010cf2f9f7 in objc_object::sidetable_release(bool, bool) ()
Run Code Online (Sandbox Code Playgroud)

游乐场示例:

import WebKit

class MockNavigationAction: WKNavigationAction {}

var navigationAction: WKNavigationAction? = MockNavigationAction()

navigationAction = nil
Run Code Online (Sandbox Code Playgroud)

非常感谢有关如何解决此问题的建议。

webkit ios swift ios15

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

标签 统计

c# ×1

collections ×1

generics ×1

ienumerable ×1

ios ×1

ios15 ×1

reflection ×1

swift ×1

webkit ×1