עבור לתוכן
View in the app

A better way to browse. Learn more.

HWzone

A full-screen app on your home screen with push notifications, badges and more.

To install this app on iOS and iPadOS
  1. Tap the Share icon in Safari
  2. Scroll the menu and tap Add to Home Screen.
  3. Tap Add in the top-right corner.
To install this app on Android
  1. Tap the 3-dot menu (⋮) in the top-right corner of the browser.
  2. Tap Add to Home screen or Install app.
  3. Confirm by tapping Install.

C#: בנאי שלא מקבל פרמטרים - אפשרי ?

Featured Replies

פורסם

אני אמור לכתוב תוכנית שמתפקדת כ-Log כלומר כותבת את ההודעות לקובץ ושומרת, כמובן שהקובץ אמור לאגור את ההודעות גם אחרי שהתוכנית נסגרת, כתבתי משהו שעובד אבל אני לא בטוח שמותר לי לעשות ככה והאם לכך התכוונו וכמו כן איך אני אמור להתשמש במתודת ה-Dispose שנכתבה לי לאחר שה-Class שלי ירש מ-IDisposable:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Collections;


namespace Log
{
public class Log : IDisposable
{
public string Msg;


public Log()
{

}


public string PrintMessage()
{
return DateTime.Now + "Message: " + this.Msg;
}


public string GetMessage(int num)
{
return "t";
}


public void AddMessage(string msg)
{
FileStream fs1 = new FileStream("LOG.txt", FileMode.Append, FileAccess.Write);
StreamWriter sw1 = new StreamWriter(fs1);
this.Msg = msg;
sw1.WriteLine(DateTime.Now + " " + "Message: " + this.Msg);
sw1.Close();
}


public void Dispose()
{

}
}


class Program
{
static void Main(string[] args)
{
Log log1 = new Log();
Console.WriteLine("Enter Text: ");
string input = Console.ReadLine();


while (input != "0")
{
log1.AddMessage(input);
input = Console.ReadLine();
}


Console.ReadLine();
}
}
}

פורסם

מה זאת אומרת "מותר"? אם זה מתקמפל, זה מותר (יכול להיות שזה לא מומלץ, אבל זה כבר סיפור אחר). אין שום בעיה לעשות בנאי שלא מקבל פרמטרים. שים לב שאם למחלקה שלך אין שום בנאים בכלל, אוטומטית נוצר לה בנאי ריק שלא מקבל פרמטרים (בדיוק כמו שאתה עשית), ככה שהבנאי שלך לא נחוץ.

לגבי IDisposable, אתה צריך לדעת איך ומתי אמורים לממש אותו... במשפט אחד - המחלקה שלך צריכה להיות IDisposable רק אם יש לה איברים (members) שצריך לעשות להם Dispose בסוף השימוש (או פונקציה שקולה ל-Dispose). במקרה שלך אין למחלקה שום איבר כזה.

חוץ מזה, כשבאמת תצטרך לממש IDisposable, קרא מה שכאן:

http://msdn.microsoft.com/en-us/library/fs2xkftw.aspx

פורסם
  • מחבר

תודה רבה

ארכיון

דיון זה הועבר לארכיון ולא ניתן להוסיף בו תגובות חדשות.

דיונים חדשים

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.