无法将“string”隐式转换为泛型类型<t> </t>

时间:2011-11-13 05:37:34

标签: .net generics

我们有以下课程

public class MyPropertyBase
{
    public int StartOffset { get; set; }
    public int EndOffset { get; set; }
}

public class MyProperty<T> : MyPropertyBase
{
    public MyProperty(T propertyValue)
    {
        PropertyValue = propertyValue;
    }

    public T PropertyValue { get; set; }
}

class BE
{
    public MyProperty<string> FUND_CITY { get; set; }

    public MyProperty<int> SomeOtherProperty { get; set; }

    public List<MyPropertyBase> MyDataPoints { get; set; }
}

当我将BE的实例创建为objBE并指定objBE.FUND_CITY="Some Value"时,会出现错误:

  

“无法将”字符串“转换为MyProperty。

5 个答案:

答案 0 :(得分:3)

这是因为FUND_CITY实例BE的{​​{1}}成员类型为objBE而非MyProperty<string>,因此您尝试将值分配给string错误的类型。

你可以这样做:

objBE.FUND_CITY.PropertyValue = "Some Value";

这可能会产生您正在寻找的结果,否则您可以直接设置该成员,您可以执行以下操作。

objBE.FUND_CITY = new MyProperty<string>("Some Value");

或者如果你想使用隐式输入..

objBE.FUND_CITY = new MyProperty("Some Value");

答案 1 :(得分:3)

如果您需要该语法,则需要隐式转换。

示例:

public class MyProperty<T> : MyPropertyBase
{
    public MyProperty(T propertyValue)
    {
        PropertyValue = propertyValue;
    }

    public T PropertyValue { get; set; }

    public static implicit operator MyProperty<T>(T t)
    {
       return new MyProperty(t);
    }
}

答案 2 :(得分:1)

这是对的。 FUND_CITY不是string,而是MyProperty<string>类型。你需要这样做:

objBE.FUND_CITY = new MyProperty<string>("Some Value").

或者,如果你有一个无参数构造函数,你可以这样做:

objBE.FUND_CITY = new MyProperty<string>();
objBE.FUND_CITY.PropertyValue = "Some Value";

答案 3 :(得分:1)

尝试objBE.FundCity = new MyProperty(“SomeValue”);

答案 4 :(得分:0)

根据您当前的设计,您需要编写

objBE.FUND_CITY.PropertyValue = "Some Value";

这是因为FUND_CITY的{​​{1}}属性不是BE,而是string,它本身有一个名为MyProperty<string>的属性。