假设我需要在Xamarin中实现一些特定于平台的代码,但是有一个返回类型特定于我需要解释的平台。你会怎么做?我曾尝试为该类型编写接口,但似乎无法使其正常工作。
IAuthService.cs
namespace MyApp.Interfaces
{
public interface IAuthService
{
Task<IUser> signInWithEmailAndPassword(string email, string password);
}
public interface IUser
{
string DisplayName { get; }
string PhoneNumber { get; }
string Email { get; }
string Uid { get; }
}
}
AuthService_Droid.cs
[assembly: Dependency(typeof(AuthService))]
namespace MyApp.Droid
{
public class AuthService : IAuthService
{
public async Task<IUser> signInWithEmailAndPassword(string email, string password)
{
FirebaseAuth auth = FirebaseAuth.Instance;
IAuthResult result = await auth.SignInWithEmailAndPasswordAsync(email, password);
IUser user = result.User;
return user;
}
}
}
尝试分配result.User
时看到错误
无法将类型'Firebase.Auth.FirebaseUser'隐式转换为 “ MyApp.Interfaces.IUser”。存在显式转换( 你错过了演员吗?)
有可能吗?还是只能跨平台发送基本类型?
答案 0 :(得分:2)
在您的共享代码中,
public class MyUser : IUser {
... implement properties ...
}
然后在您的平台代码中
IUser user = new MyUser() {
DisplayName = result.User.DisplayName,
... assign other properties from result.User ...
};