Frage

I'm implementing the following WCF service

    [ServiceContract]
    [ServiceKnownType(typeof(Person))]
    public interface IPersonService
    {
        [OperationContract]
        IPerson GetPerson();
    }
   [AspNetCompatibilityRequirements(RequirementsMode =AspNetCompatibilityRequirementsMode.Allowed)]
   public class PersonService : IPersonService
   {
        public IPerson GetPerson()
        {
            return new Person();
        }
    }

The interface IPerson is defined

public interface IPerson
    {
        string FirstName { get; set; }
        string LastName { get; set; }
    }

and the class Person that implements the interface is defined as

[DataContract]
    public class Person : IPerson
    {
        [DataMember]
        public string FirstName { get; set; }
        [DataMember]
        public string LastName { get; set; }
    }

The problem is when I reference the PersonService and call the GetPerson method, what I get as a result is type object not type Person. To get type Person I have to do an explicit cast.

static void Main(string[] args)
        {
            var proxy = new PersonServiceReference.PersonServiceClient();
            PersonServiceReference.Person person = (PersonServiceReference.Person)proxy.GetPerson();
        }

Is there any way I can get the GetPerson web method to return an IPERSON type without doing the explicit cast?

War es hilfreich?

Lösung

Do you have more than one class implementing IPerson interface?

If you know the return type of the GetPerson function is always going to be Person, why have IPerson? Simply change the interface of the method on the IPersonService interface to return Person instead of IPerson and update the service references in your clients. This will give you a GetPerson that returns Person object (and therefore no need to cast).

If, in the other hand, you are going to have more than one class of type IPerson (like Employee, Customer, Person, etc..) AND the method GetPerson CAN return more than one of those types, then casting is your only way out of the situation, since the object type of the return can morph into any of the types implementing IPerson.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top