【问题标题】:Return the datatype of a property based on entity name and property name根据实体名称和属性名称返回属性的数据类型
【发布时间】:2019-07-29 14:31:06
【问题描述】:

我正在尝试根据实体名称和属性名称检索属性的数据类型;两者都被声明为字符串。

以下面的实体为例

public class Client
{
    public string Name { get; set; }
    public string Phone { get; set; }
}

我希望从“客户端”和“电话”返回“字符串”。

【问题讨论】:

    标签: c# asp.net entity-framework asp.net-core entity-framework-core


    【解决方案1】:

    可以这样做:

    System.Reflection.PropertyInfo nameProp = typeof(Client).GetProperty("Name");
    Type nameType = nameProp.PropertyType; // nameType  will be System.String
    

    如果您不知道确切的类型,请使用:

    var type = Type.GetType("Namespace.ClassName, Assembly");
    

    【讨论】:

    • 如果我无法声明 typeof(Client) 而是将 type 作为字符串传递怎么办? typeof("客户")
    • 然后输入 = Type.GetType("MyNamespace.MyEntity, MyEntityAssembly")
    • @TrystanWilcock 我的回答对您的问题有帮助吗?
    【解决方案2】:

    对于Type.GetType,我们需要传递全名,如果您更喜欢Client 这样的短名称而不是Namespace.Client,您可以尝试下面的代码从程序集中检索类型。

    Assembly assembly  = Assembly.GetExecutingAssembly();
    var type = assembly.GetTypes().ToList().FirstOrDefault(t => t.Name == "Client");
    System.Reflection.PropertyInfo nameProp = type.GetProperty("Name");
    string typeName = nameProp.PropertyType.Name; // nameType  will be System.String
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-27
      • 1970-01-01
      • 2010-09-30
      • 1970-01-01
      • 2020-09-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-08
      相关资源
      最近更新 更多