开发者

C# Implementing and converting interfaces

Ive a class that implement the IMarcas interface:

  public class BaseQuestao : IMarcas
    {
        public string TxtMarca
        {
            get;
            set;
        }
    }

Where TxtMarca property is an assignture from that interface.

Problem is that when i try to execute follow code is 开发者_如何学Pythonsays that BasesQuestao is NOT IMarcas:

BaseQuestao bs = new BaseQuestao();
IMarcas brand =  bs as IMarcas;
if (brand != null)
{
    bs.TxtMarca = "voila";
}

Any ideias?


As others have said, you're using the wrong variable (bs instead of brand) - but it would have worked either way.

Here's an example with the code corrected:

using System;

public interface IMarcas
{
    string TxtMarca { get; set; }
}

public class BaseQuestao : IMarcas
{
    public string TxtMarca
    {
        get;
        set;
    }
}

class Test
{
    static void Main()
    {
        BaseQuestao bs = new BaseQuestao();
        IMarcas brand =  bs as IMarcas;
        if (brand != null)
        {
            brand.TxtMarca = "voila";
            Console.WriteLine("Done");
        }
    }
}

and even with the original code:

if (bs != null)
{
    bs.TxtMarca = "voila";
    Console.WriteLine("Done");
}

... it's still fine.


After you cast bs to an IMarcas as brand, you then check if bs is null, not brand. You should check if brand is null to see if the cast succeeded.

Other than that it should work just fine. If it still doesn't work, please post more code/context.


Try

if (brand != null)


Check your code, as the above code is fine

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜