如何将字符串转换为类属性

时间:2020-03-13 15:26:16

标签: c# casting entity-framework-core

我有一个数据库模型(使用efcore在模型和数据库之间转换),该模型包含一个可以是三个值的字符串。

为了更好地控制进入db的字符串值,我创建了一个枚举枚举(在C#中无法实现,所以I followed this model)。

public class MyModelClass 
{
    public int Id { get; protected set; }
    public string MyString { get; protected set; }

    public MyModelClass(int id, MyTranslatingType type)
    {
        Id = id;
        MyString = type.Value;
    }

    public class MyTranslatingType
    {
        private MyTranslatingType(string value) { Value = value; }

        public string Value { get; set; }

        public static MyTranslatingType FirstType
            => new MyTranslatingType(nameof(FirstType));

        public static MyTranslatingType SecondType
            => new MyTranslatingType (nameof(SecondType));

        public static MyTranslatingType ThirdType
            => new MyTranslatingType (nameof(ThirdType));
    }
}

但是,当我尝试从数据库中获取值时,我不能只转换它们或使用typeof(),因为它们是属性,而不是传统的枚举/类型。

我尝试过

// error saying it can't convert [PropertyInfo][2] to MyModelClass.MyTranslatingType
MyModelClass.MyTranslatingType myType = typeof(MyModelClass.MyTranslatingType).GetProperty("ThirdType");

// error saying it can't convert string to MyModelClass.MyTranslatingType
MyModelClass.MyTranslatingType myType = (MyModelClass.MyTranslatingType)"ThirdType";

如何将"ThirdType"的字符串强制转换为MyModelClass.MyTranslatingType.ThirdType之类的属性?

换句话说,我希望myType等于MyModelClass.MyTranslatingType.ThirdType
var myType = (MyModelClass.MyTranslatingType)"ThirdType"

4 个答案:

答案 0 :(得分:1)

我认为您正在寻找某种工厂模式。您可以这样做:

public class MyTranslatingType
{
    // A dictionary of methods to get the relevant type
    private static Dictionary<string, Func<MyTranslatingType>> _typeFactory = 
        new Dictionary<string, System.Func<MyModelClass.MyTranslatingType>>
        {
            { nameof(FirstType), () => new MyTranslatingType(nameof(FirstType)) },
            { nameof(SecondType), () => new MyTranslatingType(nameof(SecondType)) },
            { nameof(ThirdType), () => new MyTranslatingType(nameof(ThirdType)) },
        };

    // Method to get the type required
    public static MyTranslatingType GetMyTranslatingType(string type)
    {
        if (_typeFactory.TryGetValue(type, out var getType))
        {
            return getType();
        }

        throw new ArgumentOutOfRangeException(nameof(type), $"Cannot get type for {type}");
    }
}

您可以这样使用它:

var myType = MyModelClass.MyTranslatingType.GetMyTranslatingType("FirstType");

此方法比您的方法更干净,因为我们现在不再有大量的公共静态方法来获取类型。

以下是使用const而不是属性的完整版本:

public class MyTranslatingType
{
    private const string FirstType = "FirstType";
    private const string SecondType = "SecondType";
    private const string ThirdType = "ThirdType";

    private MyTranslatingType(string value) { Value = value; }

    public string Value { get; set; }

    // A dictionary of methods to get the relevant type
    private static Dictionary<string, Func<MyTranslatingType>> _typeFactory = 
        new Dictionary<string, System.Func<MyModelClass.MyTranslatingType>>
        {
            { FirstType, () => new MyTranslatingType(FirstType) },
            { SecondType, () => new MyTranslatingType(SecondType) },
            { ThirdType, () => new MyTranslatingType(ThirdType) },
        };

    // Method to get the type required
    public static MyTranslatingType GetMyTranslatingType(string type)
    {
        if (_typeFactory.TryGetValue(type, out var getType))
        {
            return getType();
        }

        throw new ArgumentOutOfRangeException(nameof(type), $"Cannot get type for {type}");
    }
}

答案 1 :(得分:1)

如果要将一种类型转换为另一种类型:将字符串转换为MyTranslatingType,则需要隐式或显式转换运算符:

public static implicit operator string(MyTranslatingType tp) => tp?.Value;
public static implicit operator MyTranslatingType(string value)
{
    return value switch
    {
        nameof(FirstType) => FirstType,
        nameof(SecondType) => SecondType,
        nameof(ThirdType) => ThirdType,
        _ => new MyTranslatingType(value)
    };
}
  • 注意,switch语句是C#8。您可以更新以使用传统的switch语法。

答案 2 :(得分:0)

typeof(MyModelClass.MyTranslatingType).GetProperty("ThirdType")返回PropertyInfo

要获取值:

var myType = (MyModelClass.MyTranslatingType)typeof(MyModelClass.MyTranslatingType).GetProperty("ThirdType").GetGetMethod().Invoke(null, null);

答案 3 :(得分:0)

使用系统; 使用System.Reflection;

命名空间ConsoleApp1 {

// Outer class 
public class Outer_class
{

    // Method of outer class 
    public void method1()
    {
        Console.WriteLine("Outer class method");
    }

    // Inner class 
    public class Inner_class
    {

        private Inner_class(string value) { Value = value; }

        public string Value { get; set; }

        public static Inner_class FirstType => new Inner_class(nameof(FirstType));


    }
}

class Program
{
    private const string Name = "FirstType";

    static void Main(string[] args)
    {
        PropertyInfo obj = typeof(Outer_class.Inner_class).GetProperty(Name);

        Console.WriteLine(obj.Name);

        Console.WriteLine(obj.PropertyType);


    }
}
相关问题