C# PCL中缺少的方法

C# PCL中缺少的方法,c#,xamarin.ios,xamarin.android,portable-class-library,C#,Xamarin.ios,Xamarin.android,Portable Class Library,我有一个非常通用的数据库插入/查询,作为一个非PCL方法可以很好地工作。我正在尝试将它转移到一个PCL项目中,对于大多数代码来说,没有问题 但是,我发现缺少各种System.Type方法,我不知道如何解决这些问题 我遇到问题的三种方法是GetMethod、GetProperties和GetCustomAttributesIgnoreAttribute与Length属性一样丢失 我知道78配置文件对反射进行了更改,但我没有发现任何东西可以替代代码使用扩展方法,MvvmCross就是这样处理的

我有一个非常通用的数据库插入/查询,作为一个非PCL方法可以很好地工作。我正在尝试将它转移到一个PCL项目中,对于大多数代码来说,没有问题

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

我遇到问题的三种方法是
GetMethod
GetProperties
GetCustomAttributes
IgnoreAttribute
Length
属性一样丢失

我知道78配置文件对反射进行了更改,但我没有发现任何东西可以替代代码

使用扩展方法,MvvmCross就是这样处理的


您可以在PCL项目中创建接口
DirectReflectionHelper

/// <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);
    }
//
///此接口提供了一些PCL中不支持的反射方法。
/// 
公共接口定向帮助器
{
/// 
///获取给定类型的。
/// 
///类型。
///方法的名称。
///返回方法信息。
MethodInfo GetMethodInfo(类型类型,字符串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;
        }
    }
}
[程序集:Xamarin.Forms.Dependency(typeof(DroidReflectionHelper))]
名称空间App1.Droid
{
/// 
///Android平台的应用程序实现。
/// 
公共类DroidReflectionHelper:DirectReflectionHelper
{
/// 
///获取给定类型的。
/// 
///类型。
///方法的名称。
///返回方法信息。
public MethodInfo GetMethodInfo(类型,字符串methodName)
{
MethodInfo MethodInfo=type.GetMethod(methodName);
返回方法信息;
}
}
}

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

您可以像使用System.Reflection一样使用System.Reflection;在你的班级档案中

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

PM> Install-Package System.Reflection.TypeExtensions
现在您可以获得如下方法:

GetProperties - typeof(Something).GetProperties();

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

依赖于平台的事情应该通过依赖注入来处理,如Xamarin文章所示,考虑到这与其说是一个xam表单问题,不如说是一个反射问题,有没有办法将缺少的方法作为PCL的一部分来实现(例如,可以通过文件管理器完成)?您将无法向预定义的PCL配置文件中添加任何内容。因此解决方法完全相同。Xamarin文章不仅适用于Xamarin.Forms。您可以创建一个接口,该接口将提供
GetMethodInfo
方法。之后,您应该为每个特定于平台的项目实现它。