I have two methods:
static public async Task Delete( Guid id, string path, ViewModelCollection<ProfileData> collection )
{
var jsonText = await File.ReadAllTextAsync( path );
var jsonList = JsonConvert.DeserializeObject<List<ProfileData>>( jsonText );
if ( jsonList != null && jsonList.Any() )
{
var itemToDelete = jsonList
.FirstOrDefault( x => x.Id == id );
if ( itemToDelete != null )
{
jsonList.Remove( itemToDelete );
}
}
var output = JsonSerializer.Serialize( jsonList );
await File.WriteAllTextAsync( path, output );
var item = collection.FirstOrDefault( x => x.Id == id );
if ( item != null ) collection.Remove( item );
}
static public async Task Delete( Guid id, string path, ViewModelCollection<SubscriptionData> collection )
{
var jsonText = await File.ReadAllTextAsync( path );
var jsonList = JsonConvert.DeserializeObject<List<SubscriptionData>>( jsonText );
if ( jsonList != null && jsonList.Any() )
{
var itemToDelete = jsonList
.FirstOrDefault( x => x.Id == id );
if ( itemToDelete != null )
{
jsonList.Remove( itemToDelete );
}
}
var output = JsonSerializer.Serialize( jsonList );
await File.WriteAllTextAsync( path, output );
var item = collection.FirstOrDefault( x => x.Id == id );
if ( item != null ) collection.Remove( item );
}
The problem, I think, is immediately visible - ProfileData simply changes to SubscriptionData. Question: how to avoid this?
I wanna have this:
static public async Task Delete<T>(...){... var itemToDelete = jsonList.FirstOrDefault(x => x.Id == id ...)
The problem is x.Id of unknown class
CodePudding user response:
The problem is x.Id of unknown class
Declare an interface IHasId
which defines your Id
property, and make sure that both ProfileData
and SubscriptionData
implement that interface.
You can then constrain your generic method declaration as follows:
static public async Task Delete<T>(...) where T : IHasId
{ ... }
(Obviously, if you already have a base class for ProfileData
and SubscriptionData
which defines the Id
property, you can just constrain your generic parameter to that base class.)