【问题标题】:Missing methods in PCLPCL 中缺少方法
【发布时间】:2015-01-23 23:30:40
【问题描述】:

我有一个非常通用的数据库插入/查询,它可以作为非 PCL 方法正常工作。我正在尝试将其移至 PCL 项目,并且对于大多数代码而言,没有问题。

但是,我发现缺少各种 System.Type 方法,我不知道如何解决这些问题。

我遇到问题的三种方法是GetMethodGetPropertiesGetCustomAttributes。缺少 IgnoreAttributeLength 属性。

我知道使用 78 配置文件对反射进行了更改,但我没有找到任何替换代码的东西

【问题讨论】:

  • 平台依赖的东西应该通过依赖注入来处理,见Xamarin文章developer.xamarin.com/guides/cross-platform/…
  • 尽管这更像是一个反射问题而不是一个 xam 表单问题,有没有办法将缺少的方法作为 PCL 的一部分来实现(例如可以通过文件管理器完成)?
  • 您将无法向预定义的 PCL 配置文件添加任何内容。所以解决方法是完全相同的。该 Xamarin 文章不仅适用于 Xamarin.Forms。
  • 您可以创建一个接口,该接口将提供GetMethodInfo 方法。之后,您应该为每个特定于平台的项目实施它。

标签: c# xamarin.ios xamarin.android portable-class-library


【解决方案1】:

使用扩展方法,this 是 MvvmCross 的处理方式。

GetMethod

GetProperties

GetCustomAttributes

【讨论】:

    【解决方案2】:

    您可以在您的 PCL 项目中创建一个接口 IReflectionHelper

    /// <summary>
    /// This interface provides some reflection methods which are not supported into PCL.
    /// </summary>
        public interface IReflectionHelper
        {
            /// <summary>
            /// Get <see cref="MethodInfo"/> for the given type.
            /// </summary>
            /// <param name="type">The type.</param>
            /// <param name="methodName">The name of the method.</param>
            /// <returns>Returns method info.</returns>
            MethodInfo GetMethodInfo(Type type, string methodName);
        }
    

    然后您应该为每个特定平台实现它。这是 Android 的示例。

    [assembly: Xamarin.Forms.Dependency(typeof(DroidReflectionHelper))]
    namespace App1.Droid
    {
        /// <summary>
        /// Implementation of the <see cref="IReflectionHelper"/> for Android platform.
        /// </summary>
        public class DroidReflectionHelper : IReflectionHelper
        {
            /// <summary>
            /// Get <see cref="MethodInfo"/> for the given type.
            /// </summary>
            /// <param name="type">The type.</param>
            /// <param name="methodName">The name of the method.</param>
            /// <returns>Returns method info.</returns>
            public MethodInfo GetMethodInfo(Type type, string methodName)
            {
                MethodInfo methodInfo = type.GetMethod(methodName);
                return methodInfo;
            }
        }
    }
    

    我在示例中使用了服务定位器。你可以在这里阅读更多信息:Introduction to DependencyService

    【讨论】:

      【解决方案3】:

      您可以像使用 System.Reflection 一样使用 System.Reflection;在你的类文件中。

      然后通过以下命令使用以下命令安装TypeExtensions:

      PM> Install-Package System.Reflection.TypeExtensions
      

      现在你可以得到如下方法:

      GetProperties - typeof(Something).GetProperties();
      

      GetCustomAttribute - CustomAttributeExtensions.GetCustomAttribute(参数可能不同)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-09-15
        • 1970-01-01
        • 1970-01-01
        • 2018-06-13
        • 1970-01-01
        • 2018-12-06
        • 1970-01-01
        • 2021-11-04
        相关资源
        最近更新 更多